Skip to content

Commit d2465cd

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 1592dab commit d2465cd

File tree

5 files changed

+62
-35
lines changed

5 files changed

+62
-35
lines changed

searches/README.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,18 +118,18 @@ The acceptance of worse solutions helps escape local minima, and this tendency d
118118

119119
### Advantages
120120

121-
✓ Can escape local minima
122-
✓ Simple to implement
123-
✓ Widely applicable
124-
✓ No gradient required
125-
✓ Works with discrete and continuous problems
121+
✓ Can escape local minima
122+
✓ Simple to implement
123+
✓ Widely applicable
124+
✓ No gradient required
125+
✓ Works with discrete and continuous problems
126126

127127
### Disadvantages
128128

129-
✗ Requires careful parameter tuning
130-
✗ No guarantee of finding global optimum
131-
✗ Can be slow for very large problems
132-
✗ Performance depends on cooling schedule
129+
✗ Requires careful parameter tuning
130+
✗ No guarantee of finding global optimum
131+
✗ Can be slow for very large problems
132+
✗ Performance depends on cooling schedule
133133

134134
## Other Search Algorithms
135135

searches/SIMULATED_ANNEALING_GUIDE.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,9 @@ for rate in cooling_rates:
201201
cooling_rate=rate,
202202
max_iterations=1000
203203
)
204-
204+
205205
best_state, best_cost = optimizer.optimize()
206-
206+
207207
print(f"\nCooling rate: {rate}")
208208
print(f" Final cost: {best_cost:.6f}")
209209
print(f" Iterations: {optimizer.iteration}")
@@ -229,7 +229,7 @@ def portfolio_risk(weights):
229229
total = sum(weights)
230230
if abs(total - 1.0) > 0.01:
231231
return 1e6 # Penalty for invalid weights
232-
232+
233233
# Simple risk calculation (in reality, use covariance matrix)
234234
risk = sum(w**2 * std**2 for w, (_, std) in zip(weights, stocks))
235235
return risk
@@ -290,7 +290,7 @@ print(f"Maximum profit: {max_profit:.2f}")
290290

291291
### Temperature Parameters
292292

293-
- **Initial Temperature**:
293+
- **Initial Temperature**:
294294
- Higher = more exploration, slower convergence
295295
- Typical range: 100 - 10000
296296
- Start high for complex problems
@@ -311,7 +311,7 @@ print(f"Maximum profit: {max_profit:.2f}")
311311
2. **Use slower cooling** (higher rate) for complex landscapes
312312
3. **Increase iterations** if not converging
313313
4. **Multiple runs** can help due to randomness
314-
5. **Monitor acceptance rate**:
314+
5. **Monitor acceptance rate**:
315315
- Too high? Increase cooling rate
316316
- Too low? Increase initial temperature
317317

searches/simulated_annealing_tsp.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -273,17 +273,23 @@ def _create_widgets(self):
273273
)
274274

275275
ttk.Button(
276-
control_frame, text="Generate Cities", command=self._generate_cities_from_input
276+
control_frame,
277+
text="Generate Cities",
278+
command=self._generate_cities_from_input,
277279
).grid(row=0, column=2, padx=5)
278280

279281
# Parameters
280-
ttk.Label(control_frame, text="Initial Temp:").grid(row=0, column=3, padx=(20, 5))
282+
ttk.Label(control_frame, text="Initial Temp:").grid(
283+
row=0, column=3, padx=(20, 5)
284+
)
281285
self.temp_var = tk.StringVar(value="1000")
282286
ttk.Entry(control_frame, textvariable=self.temp_var, width=10).grid(
283287
row=0, column=4
284288
)
285289

286-
ttk.Label(control_frame, text="Cooling Rate:").grid(row=0, column=5, padx=(20, 5))
290+
ttk.Label(control_frame, text="Cooling Rate:").grid(
291+
row=0, column=5, padx=(20, 5)
292+
)
287293
self.cooling_var = tk.StringVar(value="0.995")
288294
ttk.Entry(control_frame, textvariable=self.cooling_var, width=10).grid(
289295
row=0, column=6
@@ -299,7 +305,10 @@ def _create_widgets(self):
299305
self.start_button.pack(side=tk.LEFT, padx=5)
300306

301307
self.pause_button = ttk.Button(
302-
button_frame, text="Pause", command=self._pause_optimization, state=tk.DISABLED
308+
button_frame,
309+
text="Pause",
310+
command=self._pause_optimization,
311+
state=tk.DISABLED,
303312
)
304313
self.pause_button.pack(side=tk.LEFT, padx=5)
305314

@@ -346,7 +355,8 @@ def _setup_plots(self):
346355
def _generate_random_cities(self, n: int):
347356
"""Generate n random cities."""
348357
self.cities = [
349-
City(random.uniform(0, 100), random.uniform(0, 100), f"C{i}") for i in range(n)
358+
City(random.uniform(0, 100), random.uniform(0, 100), f"C{i}")
359+
for i in range(n)
350360
]
351361
self._plot_initial_cities()
352362

@@ -478,13 +488,14 @@ def _update_plots(self):
478488
# Plot route
479489
self.ax_route.plot(x_coords, y_coords, "b-", alpha=0.6, linewidth=2)
480490
self.ax_route.scatter(
481-
[city.x for city in self.cities], [city.y for city in self.cities],
482-
c="red", s=100, zorder=2
491+
[city.x for city in self.cities],
492+
[city.y for city in self.cities],
493+
c="red",
494+
s=100,
495+
zorder=2,
483496
)
484497

485-
self.ax_route.set_title(
486-
f"Best Route (Distance: {route.total_distance():.2f})"
487-
)
498+
self.ax_route.set_title(f"Best Route (Distance: {route.total_distance():.2f})")
488499
self.ax_route.set_xlabel("X")
489500
self.ax_route.set_ylabel("Y")
490501
self.ax_route.set_aspect("equal")
@@ -533,7 +544,10 @@ def main():
533544
print("=" * 60)
534545

535546
# Create 10 random cities
536-
cities = [City(random.uniform(0, 100), random.uniform(0, 100), f"City{i}") for i in range(10)]
547+
cities = [
548+
City(random.uniform(0, 100), random.uniform(0, 100), f"City{i}")
549+
for i in range(10)
550+
]
537551

538552
print(f"\nSolving TSP for {len(cities)} cities...")
539553

searches/simulated_annealing_with_gui.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,9 @@ def _generate_neighbor(self) -> list[float]:
8585
zip(self.current_state, self.bounds)
8686
):
8787
# Adaptive step size based on temperature
88-
step_size = (max_val - min_val) * 0.1 * (self.temperature / self.initial_temp)
88+
step_size = (
89+
(max_val - min_val) * 0.1 * (self.temperature / self.initial_temp)
90+
)
8991
new_val = current_val + random.uniform(-step_size, step_size)
9092
# Ensure within bounds
9193
new_val = max(min_val, min(max_val, new_val))
@@ -214,16 +216,22 @@ def _create_widgets(self):
214216
width=20,
215217
)
216218
problem_combo.grid(row=0, column=1, padx=5)
217-
problem_combo.bind("<<ComboboxSelected>>", lambda e: self._load_default_problem())
219+
problem_combo.bind(
220+
"<<ComboboxSelected>>", lambda e: self._load_default_problem()
221+
)
218222

219223
# Parameters
220-
ttk.Label(control_frame, text="Initial Temp:").grid(row=0, column=2, padx=(20, 5))
224+
ttk.Label(control_frame, text="Initial Temp:").grid(
225+
row=0, column=2, padx=(20, 5)
226+
)
221227
self.temp_var = tk.StringVar(value="1000")
222228
ttk.Entry(control_frame, textvariable=self.temp_var, width=10).grid(
223229
row=0, column=3
224230
)
225231

226-
ttk.Label(control_frame, text="Cooling Rate:").grid(row=0, column=4, padx=(20, 5))
232+
ttk.Label(control_frame, text="Cooling Rate:").grid(
233+
row=0, column=4, padx=(20, 5)
234+
)
227235
self.cooling_var = tk.StringVar(value="0.95")
228236
ttk.Entry(control_frame, textvariable=self.cooling_var, width=10).grid(
229237
row=0, column=5
@@ -247,7 +255,10 @@ def _create_widgets(self):
247255
self.start_button.pack(side=tk.LEFT, padx=5)
248256

249257
self.pause_button = ttk.Button(
250-
button_frame, text="Pause", command=self._pause_optimization, state=tk.DISABLED
258+
button_frame,
259+
text="Pause",
260+
command=self._pause_optimization,
261+
state=tk.DISABLED,
251262
)
252263
self.pause_button.pack(side=tk.LEFT, padx=5)
253264

@@ -297,7 +308,9 @@ def _setup_plots(self):
297308

298309
self.fig.tight_layout()
299310

300-
def _get_test_function(self, name: str) -> tuple[Callable, list[float], list[tuple]]:
311+
def _get_test_function(
312+
self, name: str
313+
) -> tuple[Callable, list[float], list[tuple]]:
301314
"""
302315
Get test function, initial state, and bounds.
303316

searches/test_simulated_annealing.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,7 @@ def test_tsp_solver():
151151
# Optimal for square should be 4 (perimeter)
152152
print(f" Expected optimal: 4.0")
153153
assert final_distance <= initial_distance, "Distance increased!"
154-
assert (
155-
abs(final_distance - 4.0) < 0.1
156-
), f"Not close to optimal: {final_distance}"
154+
assert abs(final_distance - 4.0) < 0.1, f"Not close to optimal: {final_distance}"
157155
print(" ✓ Test passed!\n")
158156

159157
# Test with more cities
@@ -177,7 +175,9 @@ def test_tsp_solver():
177175
print(f"\n Initial distance: {initial_distance:.4f}")
178176
print(f" Final distance: {final_distance:.4f}")
179177
print(f" Improvement: {initial_distance - final_distance:.4f}")
180-
print(f" Improvement %: {100 * (initial_distance - final_distance) / initial_distance:.2f}%")
178+
print(
179+
f" Improvement %: {100 * (initial_distance - final_distance) / initial_distance:.2f}%"
180+
)
181181
print(f" Iterations: {solver.iteration}")
182182

183183
assert final_distance < initial_distance, "No improvement found!"

0 commit comments

Comments
 (0)