@@ -121,16 +121,24 @@ def _on_run(self):
121121
122122 def worker ():
123123 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
124+
125+ def progress_cb (step , best_cost , current_cost ):
126+ # schedule a plot update on the main thread
127+ self .after (0 , lambda : self ._update_plot_partial (step , best_cost ))
128+
129+ best , cost , history = sa .optimize (stop_event = self .stop_flag , progress_callback = progress_cb )
130+ # update final plot on main thread
126131 self .after (0 , lambda : self ._on_complete (best , cost , history ))
127132
128133 t = threading .Thread (target = worker , daemon = True )
129134 t .start ()
130135
131136 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." )
137+ # set stop flag; optimizer will stop cooperatively
138+ self .stop_flag .set ()
139+ self .stop_btn .config (state = tk .DISABLED )
140+ self .run_btn .config (state = tk .NORMAL )
141+ messagebox .showinfo ("Stop" , "Stop requested; optimizer will stop shortly." )
134142
135143 def _on_complete (self , best , cost , history ):
136144 x = list (range (len (history .get ("best_costs" , []))))
@@ -147,6 +155,23 @@ def _on_complete(self, best, cost, history):
147155 self .run_btn .config (state = tk .NORMAL )
148156 self .stop_btn .config (state = tk .DISABLED )
149157
158+ def _update_plot_partial (self , step : int , best_cost : float ):
159+ # Append a new point to plot (x=step, y=best_cost)
160+ # We'll redraw full plot for simplicity
161+ line_x = list (range (len (self .ax .lines [0 ].get_xdata ()) + 1 )) if self .ax .lines else [step ]
162+ if self .ax .lines :
163+ ydata = list (self .ax .lines [0 ].get_ydata ())
164+ ydata .append (best_cost )
165+ else :
166+ ydata = [best_cost ]
167+ self .ax .clear ()
168+ self .ax .plot (line_x , ydata , label = "best_cost" )
169+ self .ax .set_xlabel ("Iterations" )
170+ self .ax .set_ylabel ("Best cost" )
171+ self .ax .grid (True )
172+ self .ax .legend ()
173+ self .canvas .draw ()
174+
150175
151176def main ():
152177 app = SA_GUI ()
0 commit comments