-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
458 lines (361 loc) · 17.1 KB
/
main.py
File metadata and controls
458 lines (361 loc) · 17.1 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import datetime
from ttkbootstrap import Style
import ttkbootstrap as tb
from matplotlib.figure import Figure
from sklearn.cluster import KMeans
from PIL import Image, ImageTk, ImageDraw
import seaborn as sns
from kneed import KneeLocator
import matplotlib.cm as cm
import numpy as np
from matplotlib.collections import LineCollection
from collections import Counter
from scipy.spatial import distance
class VisitorEx(tk.Tk):
def __init__(self):
super().__init__()
self.style = Style()
self.style.theme_use('simplex')
self.title("VisitorEx 1.0")
self.geometry("800x600")
self.tabControl = ttk.Notebook(self)
self.tabControl.pack(expand=1, fill="both")
initial_tab = ttk.Frame(self.tabControl)
self.tabControl.add(initial_tab, text="Home Page")
self.load_button = ttk.Button(
initial_tab,
text="Drop visitor management data",
command=self.load_csv_file,
style='success.TButton',
padding=(20, 10)
)
self.load_button.pack(padx=20, pady=20, side="bottom")
instruction_text = tk.Text(
initial_tab,
wrap=tk.WORD,
height=5,
width=60,
relief="flat",
font=("Helvetica", 14),
)
instruction_text.pack(padx=20, pady=(125, 20),
anchor='center', side='top')
text = "Welcome to "
instruction_text.insert("1.0", text)
instruction_text.insert("1.13", "VisitorEx 1.0!", "bold")
text = "\n\nPlease click the 'Drop visitor management data' button to get started."
instruction_text.insert("end", text)
instruction_text.tag_configure("center", justify="center")
instruction_text.tag_configure("bold", font=("Helvetica", 14, "bold"))
num_lines = float(instruction_text.index("end").split(".")[0])
instruction_text.tag_add("bold", "1.11", "1.24")
for i in range(1, int(num_lines) + 1):
instruction_text.tag_add("center", f"{i}.0", f"{i}.end")
instruction_text.config(
state=tk.DISABLED, highlightthickness=0, borderwidth=0)
additional_text = tk.Text(
initial_tab,
wrap=tk.WORD,
height=4,
width=60,
relief="flat",
font=("Helvetica", 14),
)
additional_text.pack(padx=20, pady=10, anchor='center', side='top')
additional_text.insert(
"1.0", "Please convert your visitor management data for the day to ")
additional_text.insert("2.0", "CSV", "bold")
additional_text.insert("3.0", " format and title it ")
additional_text.insert("4.0", "'YYYY-MM-DD (Day)", "bold")
additional_text.insert(
"5.0", " Movement' \n\n")
additional_text.insert(
"6.0", "eg. '2014-06-07 (Sat) Movement'")
additional_text.tag_configure(
"bold", font=("Helvetica", 14, "bold"))
additional_text.tag_configure("center", justify="center")
num_lines = float(additional_text.index("end").split(".")[0])
for i in range(1, int(num_lines) + 1):
additional_text.tag_add("center", f"{i}.0", f"{i}.end")
additional_text.config(
state=tk.DISABLED)
combined_text_tab = ttk.Frame(self.tabControl)
self.tabControl.add(combined_text_tab, text="Information")
text1 = tk.Text(
combined_text_tab,
wrap=tk.WORD,
height=18,
width=60,
font=("Helvetica", 15),
)
text1.pack(padx=20, pady=(50, 10), anchor='center', side='top')
text1.insert(
"1.0", "Once you have placed your file into the application, the application will churn out heatmaps of the population density within amusement park per hour.\n\nThe colored paths generated on the heatmap showcase the route taken by each pair of security guards.\n\nThere will be a minimum of 3 pairs of security guards patrolling per hour. During the 1-hour lunch/dinner break, 2 pairs of security guards will patrol per hour, while the other pair is on break.")
text1.config(state=tk.DISABLED, highlightthickness=0, borderwidth=0)
second_tab = ttk.Frame(self.tabControl)
self.tabControl.add(second_tab, text="Parkmap")
self.image_width = 1
self.image_height = 1
self.image_path = 'park.png'
img = Image.open(self.image_path)
draw = ImageDraw.Draw(img)
self.original_image_reference = ImageTk.PhotoImage(
img)
self.image_reference = ImageTk.PhotoImage(
img)
self.image_label = tk.Label(second_tab, image=self.image_reference)
self.image_label.pack(fill="both", expand=True, anchor="center")
self.graph_windows = {}
self.tab_counter = 3
self.bind("<Configure>", self.resize_image)
def resize_image_for_third_tab(self, event):
if event is None:
width, height = 850, 650
else:
width, height = event.width, event.height
if width > 0 and height > 0:
max_width = int(0.85 * width)
max_height = int(0.85 * height)
if max_width > 0 and max_height > 0:
img = Image.open(self.another_image_path)
img.thumbnail((max_width, max_height), Image.LANCZOS)
self.another_image_reference = ImageTk.PhotoImage(img)
self.another_image_label.config(
image=self.another_image_reference)
self.image_width = width
self.image_height = height
def resize_image(self, event):
width, height = event.width, event.height
max_width = int(0.8 * width)
max_height = int(0.8 * height)
if max_width > 0 and max_height > 0:
if self.image_width != width or self.image_height != height:
img = Image.open(self.image_path)
img.thumbnail((max_width, max_height), Image.LANCZOS)
self.image_reference = ImageTk.PhotoImage(img)
self.image_label.config(image=self.image_reference)
self.image_width = width
self.image_height = height
def load_csv_file(self):
file_path = filedialog.askopenfilename(
filetypes=[("CSV Files", "*.csv")]
)
if not file_path:
return
file_list = []
file_name = os.path.basename(file_path)
for i in file_name:
file_list.append(i)
split_parts = file_name.split('()')
date_part = split_parts[0].strip()
year, month, rest = list(date_part.split('-'))
rest_list = list(rest.split(' '))
day = rest_list[0]
try:
df = pd.read_csv(file_path)
df["coordinates"] = '(' + df['X'].astype(str) + \
', '+df['Y'].astype(str)+')'
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
df.set_index('Timestamp', inplace=True)
first_data = df.index[0].hour
last_data = df.index[-1].hour
official_time_ranges = []
if last_data <= 23 and first_data < last_data:
for i in range(first_data, last_data+1):
if i < 10 and i != 9:
x = '0' + str(i)
y = '0' + str(i+1)
elif i == 9:
x = '0' + str(i)
y = str(i+1)
else:
x = str(i)
y = str(i+1)
official_time_ranges.append((x, y))
for i, (x, y) in enumerate(official_time_ranges):
if int(x) >= 24 and int(y) >= 24:
official_time_ranges.pop(i)
w = int(x) - 24
z = int(y) - 24
official_time_ranges.insert(
i, ('0'+str(w), '0'+str(z)))
elif int(x) <= 24 and int(y) >= 24:
official_time_ranges.pop(i)
z = int(y) - 24
official_time_ranges.insert(i, (x, '0'+str(z)))
else:
pass
else:
for i in range(first_data, last_data + 24 + 1):
if i < 10 and i != 9:
x = '0' + str(i)
y = '0' + str(i+1)
elif i == 9:
x = '0' + str(i)
y = str(i+1)
else:
x = str(i)
y = str(i+1)
official_time_ranges.append((x, y))
for i, (x, y) in enumerate(official_time_ranges):
if int(x) >= 24 and int(y) >= 24:
official_time_ranges.pop(i)
w = int(x) - 24
z = int(y) - 24
official_time_ranges.insert(
i, ('0'+str(w), '0'+str(z)))
elif int(x) <= 24 and int(y) >= 24:
official_time_ranges.pop(i)
z = int(y) - 24
official_time_ranges.insert(i, (x, '0'+str(z)))
else:
pass
datetime_obj = datetime.datetime.strptime(
f'{year}-{month}-{day}', "%Y-%m-%d")
day_abbreviation = datetime_obj.strftime("%a")
tab_name = f'{year}-{month}-{day} ({day_abbreviation})'
tab = ttk.Frame(self.tabControl)
self.tabControl.add(tab, text=tab_name)
self.tabControl.select(tab)
remove_tab_button = ttk.Button(
tab,
text="Remove Tab",
command=lambda tab=tab: self.remove_tab(tab),
style='danger.TButton',
padding=(20, 10)
)
remove_tab_button.pack(padx=20, pady=20, side="bottom")
density_tab = ttk.Notebook(tab)
density_tab.pack(expand=1, fill="both")
date_obj = datetime.datetime.strptime(
f'{year}-{month}-{day}', "%Y-%m-%d")
next_day_obj = date_obj + datetime.timedelta(days=1)
next_day = next_day_obj.strftime("%Y-%m-%d")
for i, (start, end) in enumerate(official_time_ranges):
if start != '23':
start_time = pd.to_datetime(f'{date_obj} {start}:00:00')
end_time = pd.to_datetime(f'{date_obj} {end}:00:00')
subset_df = df[start_time:end_time]
elif start == '23':
next_day = int(day) + 1
start_time = pd.to_datetime(f'{date_obj} {start}:00:00')
end_time = pd.to_datetime(f'{next_day_obj} {end}:00:00')
subset_df = df[start_time:end_time]
occurrences = subset_df['coordinates'].value_counts()
num_top_coordinates = 100
most_frequent_coordinates = occurrences.head(
num_top_coordinates)
k_range = range(1, 15)
inertia = []
for k in k_range:
kmeans = KMeans(n_clusters=k, n_init='auto')
data = subset_df[['X', 'Y']].values
kmeans.fit(data)
inertia.append(kmeans.inertia_)
kneedle = KneeLocator(
list(k_range), inertia, curve='convex', direction='decreasing')
optimal_k = kneedle.elbow
if start == "11" or start == "12" or start == "13" or start == "19" or start == "20" or start == "21":
number_of_clusters = 2
else:
number_of_clusters = 3
km = KMeans(n_clusters=number_of_clusters)
y_predicted = km.fit_predict(subset_df[['X', 'Y']])
subset_df['cluster'] = y_predicted
xmin = subset_df['X'].min()
xmax = subset_df['X'].max()
ymin = subset_df['Y'].min()
ymax = subset_df['Y'].max()
background_image = plt.imread('map.png')
fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(background_image, extent=[xmin, xmax, ymin, ymax])
sample_size = 1000
levels = 100
color_map = cm.get_cmap('YlOrRd')
cluster_density = np.bincount(subset_df['cluster']) / len(subset_df)
for cluster_id in range(number_of_clusters):
cluster_data = subset_df[subset_df['cluster']
== cluster_id]
if len(cluster_data) > sample_size:
cluster_data = cluster_data.sample(
sample_size, random_state=42)
sns.kdeplot(
data=cluster_data,
x="X",
y="Y",
fill=True,
levels=levels,
cmap="viridis",
cbar=False,
label=f'Cluster {cluster_id} Density',
alpha=0.5,
)
plt.scatter(
km.cluster_centers_[:, 0],
km.cluster_centers_[:, 1],
color='purple',
marker='*',
s=200,
label='Centroids',
)
plt.legend()
colors = ['#e60049', '#0bb4ff', '#ffa300', 'darkgreen', 'purple']
max_connection_distance = 8
for cluster_id in range(number_of_clusters):
cluster_data = subset_df[subset_df['cluster'] == cluster_id]
occurrences = cluster_data['coordinates'].value_counts()
most_visited_coords = occurrences.head(50).index.tolist()
color = colors[cluster_id % len(colors)]
for coord in most_visited_coords:
x, y = map(float, coord.strip('()').split(', '))
for other_coord in most_visited_coords:
if other_coord != coord:
other_x, other_y = map(float, other_coord.strip('()').split(', '))
dist = distance.euclidean((x, y), (other_x, other_y))
if dist < max_connection_distance:
plt.plot([x, other_x], [y, other_y], color=color, linewidth=2)
plt.title(
f'Cluster Densities from {start}:00 to {end}:00 on {year}-{month}-{day} ({day_abbreviation})')
plt.xlabel('X')
plt.ylabel('Y')
density_map_frame = ttk.Frame(density_tab)
density_tab.add(density_map_frame,
text=f'{start}:00 - {end}:00 Density Map')
canvas = FigureCanvasTkAgg(fig, master=density_map_frame)
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
plt.close(fig)
graph_title_density = f'Cluster Densities from {start}:00 to {end}:00 on {year}-{month}-{day} ({day_abbreviation})'
canvas.get_tk_widget().bind("<Button-1>", lambda event, chart=fig,
title=graph_title_density: self.show_full_graph(chart, title))
except Exception as e:
self.show_error_message(f"Error loading CSV file: {str(e)}")
def show_error_message(self, message):
tk.messagebox.showerror("Error", message)
def show_full_graph(self, chart, title):
graph_window = tk.Toplevel(self)
graph_window.title("Full Graph")
title_text = f"Full Graph from {title}"
graph_window.title(title_text)
canvas = FigureCanvasTkAgg(chart, master=graph_window)
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
self.graph_windows[chart] = graph_window
graph_window.protocol(
"WM_DELETE_WINDOW", lambda chart=chart: self.close_graph_window(chart))
def close_graph_window(self, chart):
if chart in self.graph_windows:
graph_window = self.graph_windows[chart]
graph_window.destroy()
del self.graph_windows[chart]
def show_error_message(self, message):
tk.messagebox.showerror("Error", message)
def remove_tab(self, tab):
self.tabControl.forget(tab)
if __name__ == "__main__":
app = VisitorEx()
app.mainloop()