-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm_adapter.py
More file actions
309 lines (241 loc) · 9.27 KB
/
algorithm_adapter.py
File metadata and controls
309 lines (241 loc) · 9.27 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""
Algorithm adapters to standardize algorithm interfaces.
Wraps existing algorithms to provide consistent I/O.
"""
import time
from typing import Dict, Any
from utils.result import TSPSolution
from utils.visualizer import visualize_solution
from algorithms import bruteforce, mst, sim_annealing
from algorithms.qaoa import QAOATSPSolver
from algorithms.qaoa_ibm import QAOAIBMSolver
def run_bruteforce(graph: list, visualize: bool = False, **params) -> TSPSolution:
"""
Run brute force algorithm with standardized interface.
Args:
graph: Distance matrix (2D list)
visualize: Whether to visualize the solution
**params: Additional parameters (update_frequency, etc.)
Returns:
TSPSolution object
"""
t_start = time.perf_counter()
# Extract parameters
update_frequency = params.get('update_frequency', None)
# Run algorithm
result = bruteforce.tsp_solver_final(graph, visualize=False,
update_frequency=update_frequency)
t_end = time.perf_counter()
# Parse result: (best_cost, path_str, valid_count)
best_cost, path_str, valid_count = result
# Convert path string to list
path = None
if path_str:
path = [int(x.strip()) for x in path_str.split('->')]
# Remove duplicate start node at end if present
if len(path) > 1 and path[0] == path[-1]:
path = path[:-1]
metadata = {
'time_taken': t_end - t_start,
'valid_tours': valid_count,
'update_frequency': update_frequency
}
solution = TSPSolution(path, best_cost, 'bruteforce', metadata)
# Visualize if requested
if visualize and path:
visualize_solution(graph, path, best_cost, 'Brute Force')
return solution
def run_mst(graph: list, visualize: bool = False, **params) -> TSPSolution:
"""
Run MST approximation algorithm with standardized interface.
Args:
graph: Distance matrix (2D list)
visualize: Whether to visualize the solution
**params: Additional parameters (currently unused)
Returns:
TSPSolution object
"""
t_start = time.perf_counter()
# Run algorithm (disable its own visualization)
result = mst.tsp_solver_final(graph, visualize=False)
t_end = time.perf_counter()
# Parse result: (path, total_cost)
path, total_cost = result
metadata = {
'time_taken': t_end - t_start
}
solution = TSPSolution(path, total_cost, 'mst', metadata)
# Visualize if requested
if visualize and path:
visualize_solution(graph, path, total_cost, 'MST Approximation')
return solution
def run_sim_annealing(graph: list, visualize: bool = False, **params) -> TSPSolution:
"""
Run simulated annealing algorithm with standardized interface.
Args:
graph: Distance matrix (2D list)
visualize: Whether to visualize the solution
**params: Algorithm-specific parameters:
- sa_initial_temp: Initial temperature (default: 1000)
- sa_cooling_rate: Cooling rate (default: 0.003)
- sa_max_iter: Maximum iterations (default: 10000)
Returns:
TSPSolution object
"""
t_start = time.perf_counter()
# Extract parameters
initial_temp = params.get('sa_initial_temp', 1000)
cooling_rate = params.get('sa_cooling_rate', 0.003)
max_iter = params.get('sa_max_iter', 10000)
# Run algorithm (disable its own visualization)
result = sim_annealing.simulated_annealing_final(
graph,
initial_temp=initial_temp,
cooling_rate=cooling_rate,
max_iter=max_iter,
visualize=False
)
t_end = time.perf_counter()
# Parse result: (best_cost, path_str)
best_cost, path_str = result
# Convert path string to list
path = None
if path_str:
# Parse "0 -> 1 -> 2 -> 0" format
path = [int(x.strip()) for x in path_str.split('->')]
# Remove duplicate start node at end if present
if len(path) > 1 and path[0] == path[-1]:
path = path[:-1]
metadata = {
'time_taken': t_end - t_start,
'initial_temp': initial_temp,
'cooling_rate': cooling_rate,
'max_iter': max_iter
}
solution = TSPSolution(path, best_cost, 'sim_annealing', metadata)
# Visualize if requested
if visualize and path:
visualize_solution(graph, path, best_cost, 'Simulated Annealing')
return solution
def run_qaoa(graph: list, visualize: bool = False, **params) -> TSPSolution:
"""
Run QAOA algorithm with standardized interface.
Args:
graph: Distance matrix (2D list)
visualize: Whether to visualize the solution
**params: Algorithm-specific parameters:
- qaoa_layers: Number of QAOA layers (default: 2)
- qaoa_learning_rate: Learning rate (default: 0.01)
- qaoa_optimization_steps: Optimization steps (default: 200)
- qaoa_num_approx: ApproxTimeEvolution steps per layer; 0 uses exact evolve (default: 1)
Returns:
TSPSolution object
"""
t_start = time.perf_counter()
# Extract parameters
num_layers = params.get('qaoa_layers', 2)
num_approx = params.get('qaoa_num_approx', 1)
learning_rate = params.get('qaoa_learning_rate', 0.01)
optimization_steps = params.get('qaoa_optimization_steps', 200)
# Create solver
solver = QAOATSPSolver(
graph,
num_qaoa_layers=num_layers,
learning_rate=learning_rate,
optimization_steps=optimization_steps,
num_approx=num_approx,
)
# Run algorithm
bitstring, prob = solver.solve()
# Decode solution
path, cost = solver.decode_solution(bitstring)
t_end = time.perf_counter()
metadata = {
'time_taken': t_end - t_start,
'num_layers': num_layers,
'learning_rate': learning_rate,
'optimization_steps': optimization_steps,
'num_approx': num_approx,
'probability': prob
}
solution = TSPSolution(path, cost, 'qaoa', metadata)
# Visualize if requested
if visualize and path:
visualize_solution(graph, path, cost, 'QAOA')
return solution
def run_qaoa_ibm(graph: list, visualize: bool = False, **params) -> TSPSolution:
"""
Run QAOA algorithm on IBM Quantum hardware with standardized interface.
Args:
graph: Distance matrix (2D list)
visualize: Whether to visualize the solution
**params: Algorithm-specific parameters:
- qaoa_layers: Number of QAOA layers (default: 2)
- qaoa_optimization_steps: Optimization steps (default: 100)
- ibm_backend: IBM backend name (default: 'ibm_brisbane')
- ibm_token: IBM Quantum API token (optional)
- ibm_channel: 'ibm_cloud' or 'ibm_quantum' (default: 'ibm_cloud')
- ibm_instance: IBM Cloud instance CRN (optional)
- shots: Number of measurement shots (default: 1024)
- use_ibm_backend: If False, uses local simulation (default: True)
Returns:
TSPSolution object
"""
t_start = time.perf_counter()
# Extract parameters
num_layers = params.get('qaoa_layers', 2)
optimization_steps = params.get('qaoa_optimization_steps', 100)
ibm_backend = params.get('ibm_backend', 'ibm_brisbane')
ibm_token = params.get('ibm_token', None)
ibm_channel = params.get('ibm_channel', 'ibm_cloud')
ibm_instance = params.get('ibm_instance', None)
shots = params.get('shots', 1024)
use_ibm_backend = params.get('use_ibm_backend', True)
# Create solver
solver = QAOAIBMSolver(
graph,
num_qaoa_layers=num_layers,
optimization_steps=optimization_steps,
use_ibm_backend=use_ibm_backend,
ibm_backend=ibm_backend,
ibm_token=ibm_token,
ibm_channel=ibm_channel,
ibm_instance=ibm_instance,
shots=shots
)
# Run algorithm
bitstring, prob = solver.solve()
# Decode solution
path, cost = solver.decode_solution(bitstring)
t_end = time.perf_counter()
metadata = {
'time_taken': t_end - t_start,
'num_layers': num_layers,
'optimization_steps': optimization_steps,
'ibm_backend': ibm_backend if use_ibm_backend else 'local_simulator',
'shots': shots,
'probability': prob,
'bitstring': bitstring
}
solution = TSPSolution(path, cost, 'qaoa_ibm', metadata)
# Visualize if requested
if visualize and path:
backend_name = f"QAOA (IBM: {ibm_backend})" if use_ibm_backend else "QAOA (Local Sim)"
visualize_solution(graph, path, cost, backend_name)
return solution
# Algorithm registry
ALGORITHMS = {
'bruteforce': run_bruteforce,
'mst': run_mst,
'sim_annealing': run_sim_annealing,
'qaoa': run_qaoa,
'qaoa_ibm': run_qaoa_ibm
}
def get_algorithm(algorithm_name: str):
"""
Get algorithm function by name.
"""
if algorithm_name not in ALGORITHMS:
raise ValueError(f"Unknown algorithm: {algorithm_name}. "
f"Available algorithms: {list(ALGORITHMS.keys())}")
return ALGORITHMS[algorithm_name]