forked from IHENAWY/Shortest-Path-Expedition-Planner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
354 lines (304 loc) · 15.2 KB
/
Copy pathgui.py
File metadata and controls
354 lines (304 loc) · 15.2 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""
gui.py — Professional GUI for Shortest Path Expedition Planner
Algorithms: Dijkstra & Floyd-Warshall only
Run: python gui.py
"""
import ast, time, tkinter as tk
from tkinter import ttk, messagebox
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import networkx as nx
from graph_utils import Graph
from dijkstra import dijkstra
from floyd_warshall import floyd_warshall_with_path
# ── Palette ──────────────────────────────────────────────────────────────
BG = "#0f0f1a"
PANEL = "#161625"
CARD = "#1e1e35"
ACCENT = "#7c3aed"
ACCENT2 = "#06b6d4"
GREEN = "#10b981"
RED = "#ef4444"
ORANGE = "#f59e0b"
TXT = "#e2e8f0"
DIM = "#64748b"
NODEC = "#38bdf8"
EDGEC = "#334155"
PATHC = "#f97316"
FIGBG = "#0a0a14"
DEFAULT = """{0: [(1, 3), (2, 1)], 1: [(3, 6)], 2: [(3, 2)], 3: []}"""
def parse_graph(text):
text = text.strip()
if not text:
raise ValueError("Empty input.")
obj = ast.literal_eval(text)
if not isinstance(obj, dict):
raise ValueError("Must be a dict {node: [(nb, w), ...]}")
for k, v in obj.items():
if not isinstance(v, list):
raise ValueError(f"Node {k}: neighbors must be a list")
for item in v:
if not isinstance(item, (list, tuple)) or len(item) != 2:
raise ValueError(f"Bad entry: {item}")
return obj
class App:
def __init__(self, root):
self.root = root
self.graph = None
self.nxg = None
self.pos = {}
self._setup()
self._build()
def _setup(self):
self.root.title("⚡ Shortest Path Expedition Planner")
self.root.configure(bg=BG)
self.root.geometry("1360x850")
self.root.minsize(1000, 650)
self.root.columnconfigure(0, weight=0)
self.root.columnconfigure(1, weight=1)
self.root.rowconfigure(0, weight=1)
# ── Build UI ─────────────────────────────────────────────────────────
def _build(self):
self._build_sidebar()
self._build_canvas()
def _build_sidebar(self):
sb = tk.Frame(self.root, bg=PANEL, width=370)
sb.grid(row=0, column=0, sticky="ns", padx=(12,6), pady=12)
sb.grid_propagate(False)
# Title block
hdr = tk.Frame(sb, bg=ACCENT, height=70)
hdr.pack(fill="x", padx=8, pady=(8,4))
hdr.pack_propagate(False)
tk.Label(hdr, text="🗺 Expedition Planner", font=("Helvetica", 16, "bold"),
fg="white", bg=ACCENT).pack(expand=True)
tk.Label(sb, text="Dijkstra · Floyd-Warshall · Visual Explorer",
font=("Helvetica", 9), fg=DIM, bg=PANEL).pack(pady=(0,8))
# ── Graph input card ─────────────────────────────────────────
c1 = tk.LabelFrame(sb, text=" Graph Input ", font=("Helvetica", 10, "bold"),
fg=ACCENT2, bg=CARD, bd=0, labelanchor="nw",
padx=10, pady=8)
c1.pack(fill="x", padx=8, pady=4)
self.gtxt = tk.Text(c1, height=5, bg="#111122", fg="#67e8f9",
insertbackground=ACCENT2, font=("Courier", 10),
bd=0, wrap="word", relief="flat")
self.gtxt.insert("1.0", DEFAULT)
self.gtxt.pack(fill="x", pady=(4,6))
row_f = tk.Frame(c1, bg=CARD)
row_f.pack(fill="x")
for i, (lbl, default) in enumerate([("Start:", "0"), ("End:", "3")]):
tk.Label(row_f, text=lbl, font=("Helvetica", 10), fg=TXT, bg=CARD
).grid(row=0, column=i*2, padx=(0,4))
var = tk.StringVar(value=default)
setattr(self, ["start_var","end_var"][i], var)
tk.Entry(row_f, textvariable=var, width=6, bg="#111122", fg=ACCENT2,
insertbackground=ACCENT2, font=("Helvetica", 11), bd=0,
relief="flat").grid(row=0, column=i*2+1, padx=(0,12))
# ── Algorithm selector card ──────────────────────────────────
c2 = tk.LabelFrame(sb, text=" Algorithm ", font=("Helvetica", 10, "bold"),
fg=ACCENT2, bg=CARD, bd=0, labelanchor="nw",
padx=10, pady=8)
c2.pack(fill="x", padx=8, pady=4)
self.algo_var = tk.StringVar(value="dijkstra")
for txt, val in [("Dijkstra", "dijkstra"), ("Floyd-Warshall", "floyd_warshall")]:
tk.Radiobutton(c2, text=txt, variable=self.algo_var, value=val,
bg=CARD, fg=TXT, selectcolor=PANEL,
activebackground=CARD, activeforeground=ACCENT2,
font=("Helvetica", 10)).pack(anchor="w", pady=1)
# ── Buttons ──────────────────────────────────────────────────
bf = tk.Frame(sb, bg=PANEL)
bf.pack(fill="x", padx=8, pady=8)
btns = [
("📥 Load Graph", self.load_graph, ACCENT2),
("▶ Run Selected", self.run_selected, GREEN),
("⚡ Compare Both", self.run_both, ACCENT),
("🗑 Clear", self.clear, "#475569"),
]
for txt, cmd, clr in btns:
b = tk.Button(bf, text=txt, command=cmd, bg=clr, fg="white",
activebackground=CARD, activeforeground="white",
font=("Helvetica", 11, "bold"), bd=0, relief="flat",
cursor="hand2", pady=7)
b.pack(fill="x", pady=3)
# ── Results card ─────────────────────────────────────────────
c3 = tk.LabelFrame(sb, text=" Results ", font=("Helvetica", 10, "bold"),
fg=ACCENT2, bg=CARD, bd=0, labelanchor="nw",
padx=10, pady=8)
c3.pack(fill="both", expand=True, padx=8, pady=4)
self.result_box = tk.Text(c3, bg="#111122", fg="#67e8f9",
font=("Courier", 10), bd=0, wrap="word",
state="disabled", relief="flat")
self.result_box.pack(fill="both", expand=True, pady=4)
# Status
self.status = tk.StringVar(value="Ready — load a graph to begin.")
tk.Label(sb, textvariable=self.status, font=("Helvetica", 9),
fg=DIM, bg=PANEL, wraplength=340, justify="left"
).pack(fill="x", padx=8, pady=(0,8))
def _build_canvas(self):
cf = tk.Frame(self.root, bg=FIGBG, bd=0)
cf.grid(row=0, column=1, sticky="nsew", padx=(6,12), pady=12)
cf.rowconfigure(0, weight=1)
cf.columnconfigure(0, weight=1)
self.fig, self.ax = plt.subplots(figsize=(8,6))
self.fig.patch.set_facecolor(FIGBG)
self.ax.set_facecolor(FIGBG)
self._clean_ax()
self.canvas = FigureCanvasTkAgg(self.fig, master=cf)
self.canvas.get_tk_widget().grid(row=0, column=0, sticky="nsew")
self._placeholder()
def _clean_ax(self):
self.ax.set_xticks([]); self.ax.set_yticks([])
for s in self.ax.spines.values(): s.set_visible(False)
def _placeholder(self):
self.ax.text(0.5, 0.5, "Load a graph to visualise it here",
ha="center", va="center", color=DIM, fontsize=14,
transform=self.ax.transAxes)
self.canvas.draw()
# ── Logging ──────────────────────────────────────────────────────────
def _log(self, t):
self.result_box.config(state="normal")
self.result_box.insert("end", t + "\n")
self.result_box.see("end")
self.result_box.config(state="disabled")
def _clear_log(self):
self.result_box.config(state="normal")
self.result_box.delete("1.0", "end")
self.result_box.config(state="disabled")
def _node(self, s):
s = s.strip()
try: return int(s)
except ValueError: pass
try: return float(s)
except ValueError: return s
# ── Load / Draw ──────────────────────────────────────────────────────
def load_graph(self):
try:
adj = parse_graph(self.gtxt.get("1.0", "end"))
except Exception as e:
messagebox.showerror("Invalid Graph", str(e)); return
self.graph = Graph(adj)
self.nxg = nx.DiGraph()
for n in self.graph.nodes: self.nxg.add_node(n)
for u, v, w in self.graph.edges: self.nxg.add_edge(u, v, weight=w)
self.pos = {n: self.graph.coords[n] for n in self.graph.nodes}
self._clear_log()
self._log(f"Loaded: {self.graph.n} nodes, {len(self.graph.edges)} edges")
self._draw()
self.status.set(f"Graph loaded V={self.graph.n} E={len(self.graph.edges)}")
def _draw(self, path_edges=None, path_nodes=None, start=None, end=None):
self.ax.cla(); self._clean_ax()
if not self.nxg: self.canvas.draw(); return
nc = []
for n in self.nxg.nodes():
if n == start: nc.append(GREEN)
elif n == end: nc.append(RED)
elif path_nodes and n in path_nodes: nc.append(PATHC)
else: nc.append(NODEC)
ps = set(path_edges) if path_edges else set()
ec, ew = [], []
for u, v in self.nxg.edges():
if (u,v) in ps: ec.append(PATHC); ew.append(4.0)
else: ec.append(EDGEC); ew.append(1.5)
nx.draw_networkx_nodes(self.nxg, self.pos, ax=self.ax,
node_color=nc, node_size=900,
edgecolors="white", linewidths=2)
nx.draw_networkx_labels(self.nxg, self.pos, ax=self.ax,
font_color="white", font_size=12, font_weight="bold")
nx.draw_networkx_edges(self.nxg, self.pos, ax=self.ax,
edge_color=ec, width=ew, arrows=True, arrowsize=24,
connectionstyle="arc3,rad=0.08",
min_source_margin=24, min_target_margin=24)
el = nx.get_edge_attributes(self.nxg, "weight")
nx.draw_networkx_edge_labels(self.nxg, self.pos, edge_labels=el, ax=self.ax,
font_color=TXT, font_size=9,
bbox=dict(boxstyle="round,pad=0.2",
fc=CARD, alpha=0.8, ec="none"),
label_pos=0.35)
handles = [mpatches.Patch(color=NODEC, label="Node"),
mpatches.Patch(color=GREEN, label="Start"),
mpatches.Patch(color=RED, label="End")]
if path_nodes:
handles.append(mpatches.Patch(color=PATHC, label="Shortest Path"))
self.ax.legend(handles=handles, loc="upper right",
facecolor=CARD, edgecolor="none",
labelcolor=TXT, fontsize=9)
self.ax.set_title("Expedition Graph", color=ACCENT2,
fontsize=13, fontweight="bold", pad=12)
self.canvas.draw()
def _highlight(self, path, s, e):
if not path or len(path) < 2:
self._draw(start=s, end=e); return
pe = [(path[i], path[i+1]) for i in range(len(path)-1)]
self._draw(path_edges=pe, path_nodes=set(path), start=s, end=e)
# ── Endpoints ────────────────────────────────────────────────────────
def _endpoints(self):
if not self.graph:
messagebox.showwarning("No Graph", "Load a graph first."); return None, None
s, e = self._node(self.start_var.get()), self._node(self.end_var.get())
if s not in self.graph.adj:
messagebox.showerror("Error", f"Start '{s}' not in graph."); return None, None
if e not in self.graph.adj:
messagebox.showerror("Error", f"End '{e}' not in graph."); return None, None
return s, e
# ── Run ──────────────────────────────────────────────────────────────
def run_selected(self):
s, e = self._endpoints()
if s is None: return
algo = self.algo_var.get()
name = "Dijkstra" if algo == "dijkstra" else "Floyd-Warshall"
self._clear_log()
self._log(f"▶ {name} {s} → {e}\n")
t0 = time.perf_counter()
if algo == "dijkstra":
dist, path = dijkstra(self.graph, s, e)
else:
dist, path, _ = floyd_warshall_with_path(self.graph, s, e)
ms = (time.perf_counter() - t0) * 1000
if dist == float('inf'):
self._log("No path found.")
self._draw(start=s, end=e)
self.status.set("No path exists.")
else:
self._log(f"Distance : {dist}")
self._log(f"Path : {' → '.join(str(n) for n in path)}" if path else "Path: —")
self._log(f"Time : {ms:.4f} ms")
self._highlight(path, s, e)
self.status.set(f"{name}: distance = {dist}")
def run_both(self):
s, e = self._endpoints()
if s is None: return
self._clear_log()
self._log(f"⚡ Comparing both {s} → {e}\n")
self._log(f"{'Algorithm':<18}{'Dist':>8}{'Time(ms)':>12}")
self._log("─" * 40)
best_p, best_d = None, float('inf')
for name, fn in [("Dijkstra", lambda: dijkstra(self.graph, s, e)),
("Floyd-Warshall", lambda: floyd_warshall_with_path(self.graph, s, e))]:
t0 = time.perf_counter()
res = fn()
ms = (time.perf_counter() - t0) * 1000
dist = res[0]; path = res[1]
ds = str(dist) if dist != float('inf') else "∞"
self._log(f"{name:<18}{ds:>8}{ms:>11.4f}")
if path and dist < best_d:
best_d, best_p = dist, path
self._log("─" * 40)
if best_p:
self._log(f"\nShortest: {' → '.join(str(n) for n in best_p)}")
self._log(f"Distance: {best_d}")
self._highlight(best_p, s, e)
self.status.set(f"Both done — distance = {best_d}")
else:
self._log(f"\nNo path {s} → {e}.")
self._draw(start=s, end=e)
self.status.set("No path found.")
def clear(self):
self.ax.cla(); self._clean_ax(); self._placeholder()
self._clear_log()
self.status.set("Cleared.")
if __name__ == "__main__":
root = tk.Tk()
App(root)
root.mainloop()