-
Notifications
You must be signed in to change notification settings - Fork 0
/
GUI.py
1208 lines (1081 loc) · 56.8 KB
/
GUI.py
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import Counter
from os.path import exists
from os import getenv
import random
import threading
from anytree import Node, RenderTree, find_by_attr
from Config import Config
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import QTimer
from scipy import spatial
import pyqtgraph as pg
import PyQt5.QtWidgets as QtWidgets
from PyQt5.QtWebEngineWidgets import QWebEngineView
from RoadNetwork import RoadNetwork
from SocialNetwork import SocialNetwork
from sklearn.cluster import KMeans
from pyvis.network import Network
import networkx as nx
import time
from gui.menubar import MenuBar
from gui.queryInput import QueryInput
from gui.user import UserUI
#from gui.toolbar import Mixin as ToolbarMixin
from gui.toolbar import Toolbar, QueryToolbar, Timeline
from gui.tree import Mixin as TreeMixin
import datetime
import time
import json
class Gui(QtWidgets.QMainWindow, TreeMixin):
_instance = None
def __new__(cls):
if cls._instance is None:
print('Creating the object')
cls._instance = super(Gui, cls).__new__(cls)
return cls._instance
def __init__(self):
super(Gui, self).__init__()
# Creates config
self.config = Config()
# Plot options
pg.setConfigOptions(antialias=True)
pg.setConfigOption('background', 'white')
# A dictionary of windows, each window has it's on id
self.__windows = {}
# Stores file hierarchy data
self.__fileTreeObjects = {}
# Stores timestamps for query time calculation
self.Qstart = 0
self.Qend = 0
self.SummaryResponseTime = 0
# Stores timestamps for query time calculation
self.CTstart = 0
self.CTend = 0
self.ClusterResponseTime = 0
# Stores widget instances
self.roadGraphWidget = None
self.socialGraphWidget = None
self.socialNetWidget = QWebEngineView()
self.summarySelected = False
self.hidePOIsSelected = False
# Stores selected network instances
self.selectedRoadNetwork = None
self.selectedSocialNetwork = None
# Query user information
self.queryUser = None
self.queryKeyword = None
self.queryUserPlots = []
# Store data for interactive network
self.interactiveNetwork = nx.Graph()
# Store all network info in dict format {"NetworkName: {"Data": "Value", ...}, ..."}
self.__roadNetworks = self.config.settings["Road Networks"]
self.__socialNetworks = self.config.settings["Social Networks"]
# Store network objects
self.__roadNetworkObjs = self.createNetworkInstances(self.__roadNetworks, RoadNetwork)
self.__socialNetworkObjs = self.createNetworkInstances(self.__socialNetworks, SocialNetwork)
# Set up layout
self.layout = QtWidgets.QGridLayout(self)
self.layout.setSpacing(0)
self.sumLayout = QtWidgets.QGridLayout(self)
self.sumLayout.setSpacing(0)
self.view = QtWidgets.QWidget()
# Initializes menus
self.__menuBar()
#self.navToolbar()
#self.__queryUserButton()
self.__mainWindow()
self.__ViewStats()
# Array for plot points
self.centers = []
self.ids = []
self.toolbar = Toolbar(self)
self.__windows[3] = QtWidgets.QWidget()
self.__windows[4] = QtWidgets.QWidget()
self.__windows[6] = QtWidgets.QWidget()
self.__windows[7] = QtWidgets.QWidget()
self.queryInput = QueryInput(self, self.__windows[3], self.__windows[6])
self.queryUserToolbar = QueryToolbar(self, self.__windows[3], self.__windows[4])
self.queryUserToolbar.queryUserButton()
self.toolbar.navToolbar()
self.timeline = Timeline(self)
self.timeline.hide()
self.__queryFrames = []
self.playAnimation = False
self.communityUserPos = {}
self.previousUsers = []
# Creates the plot widgets. suffix is used when a summary graph is created, for example
def createPlots(self, suffix=""):
self.roadGraphWidget = self.win.addPlot(row=0, col=1, title=f"Road Network {suffix}")
self.roadGraphWidget.scene().sigMouseClicked.connect(self.roadGraphClick)
self.socialGraphWidget = self.win.addPlot(row=0, col=0, title=f"Social Network {suffix}")
#self.linkGraphAxis()
def roadGraphClick(self, event):
vb = self.roadGraphWidget.vb
cords = event.scenePos()
if self.roadGraphWidget.sceneBoundingRect().contains(cords):
point = vb.mapSceneToView(cords)
tree = spatial.KDTree(self.centers)
closest_point = tree.query([[point.x(), point.y()]])[1][0]
ui = UserUI(self, self.__windows[7])
ui.showClusterUsers(self.selectedSocialNetwork.getClusterUsers(self.ids[closest_point]))
def createSumPlot(self, suffix=None):
self.roadGraphWidget = self.win.addPlot(row=0, col=1, title=f"Road Network {suffix}")
# Displays main window
def __mainWindow(self):
# Set up window
screensize = self.screen().availableSize().width(), self.screen().availableSize().height()
self.setGeometry(int((screensize[0] / 2) - 500), int((screensize[1] / 2) - 300), 1000, 600)
self.setWindowTitle("Spatial-Social Networks")
self.setWindowIcon(QtGui.QIcon('Assets/favicon.ico'))
self.win = pg.GraphicsLayoutWidget()
self.sum = pg.GraphicsLayoutWidget()
with open('nx.html', 'r') as f:
html = f.read()
self.socialNetWidget.setHtml(html)
# Define default layout
self.layout.addWidget(self.win, 0, 0, 1, 2)
# self.toolbar.navToolbar()
self.view.setLayout(self.layout)
self.setCentralWidget(self.view)
# Create and set up graph widget
self.createPlots()
# Show window
self.show()
def __keywordCommunity(self):
self.queryInput.community()
def __keywordTimeCommunity(self):
self.queryInput.communityTime()
def __queryInput(self):
self.queryInput.kdQuery()
def __menuBar(self):
menu = MenuBar(self.menuBar())
menu.addMenu("File")
menu.addChild("Files", "File", shortcut="Ctrl+f", tooltip="View files", action=self.viewFiles)
menu.addMenu("View")
menu.createGroup("ViewGroup", self)
menu.addChild("Summary View", "View", group="ViewGroup", tooltip="View summary graphs", action=self.viewSummary)
menu.addChild("Full View", "View", group="ViewGroup", tooltip="View full graphs", action=self.viewSummary,
checked=True)
networks = self.getCompleteNetworks()
sNetworks = networks["Social Networks"]
rNetworks = networks["Road Networks"]
menu.addMenu("Social Networks")
menu.createGroup("SocialNetworkGroup", self)
menu.addChild("None", "Social Networks", group="SocialNetworkGroup", tooltip="Display no social network",
action=lambda j: self.displaySocialNetwork(None), checked=True)
for x in sNetworks:
menu.addChild(x, "Social Networks", group="SocialNetworkGroup",
tooltip=f"Switch to view social network {x}",
action=lambda j, a=x: self.displaySocialNetwork(a))
menu.addMenu("Road Networks")
menu.createGroup("RoadNetworkGroup", self)
menu.addChild("None", "Road Networks", group="RoadNetworkGroup", tooltip="Display no road network",
action=lambda j: self.displayRoadNetwork(None), checked=True)
for x in rNetworks:
menu.addChild(x, "Road Networks", group="RoadNetworkGroup",
tooltip=f"Switch to view road network {x}",
action=lambda j, a=x: self.displayRoadNetwork(a))
# Add menu for stats
menu.addMenu("Statistics")
menu.addChild("View", "Statistics", tooltip="View statistics", action=self.ShowStatsWindow)
menu.addMenu("Query")
menu.addChild("kd-truss", "Query", tooltip="kd-truss menu", action=self.__queryInput)
menu.addChild("Community Search", "Query", tooltip="community search menu", action=self.__keywordCommunity)
menu.addChild("Community Search w/ Time", "Query", tooltip="community search w/ time menu", action=self.__keywordTimeCommunity)
def clearView(self):
self.win.removeItem(self.roadGraphWidget)
if self.socialGraphWidget:
self.win.removeItem(self.socialGraphWidget)
if self.queryUserPlots:
self.queryUserPlots = []
self.roadGraphWidget = None
self.socialGraphWidget = None
self.timeline.hide()
def dijkstra(self, queryUser):
'''if self.selectedRoadNetwork is not None:
visited = []
numOfV = self.selectedRoadNetwork.nodeCount()
D = {v: float('inf') for v in range(numOfV)}
startVertex = self.selectedRoadNetwork.closestNode(queryUser[1][0][0], queryUser[1][0][1])
D[startVertex] = 0
pq = PriorityQueue()
pq.put((0, startVertex))
while not pq.empty():
(dist, current_vertex) = pq.get()
visited.append(current_vertex)
for neighbor in range(current_vertex - 200, current_vertex + 200):
edge = self.selectedRoadNetwork.isAnEdge(str(float(current_vertex)), str(float(neighbor)))
if edge is not None:
distance = self.selectedRoadNetwork.getEdgeDistance(str(edge))
if neighbor not in visited:
old_cost = D[neighbor]
new_cost = D[current_vertex] + float(distance)
if new_cost < old_cost:
pq.put((new_cost, neighbor))
D[neighbor] = new_cost
print(D)'''
# Handles summary view
def viewSummary(self):
# Switch view to summary
if not self.summarySelected:
self.summarySelected = True
self.clearView()
# Displays summary plots
self.createSumPlot("Summary")
self.socialNetWidget = QWebEngineView()
with open('nx.html', 'r') as f:
html = f.read()
self.socialNetWidget.setHtml(html)
# Setup summary view
self.view = QtWidgets.QWidget()
self.sumLayout = QtWidgets.QGridLayout()
self.sumLayout.setSpacing(0)
self.sumLayout.addWidget(self.socialNetWidget, 0, 0, 2,1)
self.sumLayout.addWidget(self.win, 0, 1)
self.sumLayout.setColumnStretch(0, 1)
self.sumLayout.setColumnStretch(1, 1)
self.toolbar.navToolbar()
self.view.setLayout(self.sumLayout)
self.setCentralWidget(self.view)
self.toolbar.clusterInput()
#self.__queryInput()
self.updateSummaryGraph()
self.timeline.hide()
# Switch view to main
else:
self.summarySelected = False
# Setup default view
self.view = QtWidgets.QWidget()
self.layout = QtWidgets.QGridLayout()
self.layout.setSpacing(0)
self.layout.addWidget(self.win, 0, 0, 1, 2)
# Add graph toolbars
self.toolbar.navToolbar()
self.view.setLayout(self.layout)
self.setCentralWidget(self.view)
self.toolbar.clusterInput.close()
self.clearView()
#self.queryInput.close()
self.createPlots()
# Re-visualize selected networks
if self.selectedRoadNetwork is not None:
self.selectedRoadNetwork.visualize(self.roadGraphWidget)
if self.selectedSocialNetwork is not None:
self.selectedSocialNetwork.visualize(self.socialGraphWidget, self.roadGraphWidget)
self.plotQueryUser()
self.timeline.hide()
def visualizeSummaryData(self, ids, centers, sizes, relations, popSize):
# Note: For some reason, the alpha value is from 0-255 not 0-100
self.roadGraphWidget.plot(centers[:, 0], centers[:, 1], pen=None, symbol='o', symbolSize=sizes,
symbolPen=(255, 0, 0), symbolBrush=(255, 0, 0, 125))
# Create Interactive Graph HTML File Using pyvis
queryCluster = -1
if self.queryUser is not None:
queryCluster = self.selectedSocialNetwork.getUserCluster(self.queryUser[0])
network = nx.Graph()
for i in range(0, len(centers)):
if ids[i] == queryCluster:
network.add_node(str(centers[i][0]) + str(centers[i][1]), physics=False, label=popSize[i], color='green',shape='star')
else:
network.add_node(str(centers[i][0]) + str(centers[i][1]), physics=False, label=popSize[i])
for i in range(1, len(relations[0])):
network.add_edge(str(relations[0][i]) + str(relations[1][i]),
str(relations[0][i - 1]) + str(relations[1][i - 1]))
nt = Network()
nt.from_nx(network)
nt.set_options('{"layout": {"randomSeed":5}}')
nt.save_graph('nx.html')
# LEGACY SOCIAL NETWORK GRAPH
#self.socialGraphWidget.plot(centers[:, 0], centers[:, 1], pen=None, symbol='o', symbolSize=20,
# symbolPen=(255, 0, 0), symbolBrush=(255, 0, 0, 150))
#self.socialGraphWidget.plot(relations[0], relations[1], connect='pairs', pen=(50, 50, 200, 100),
# brush=(50, 50, 200, 100))
def updateSummaryGraph(self):
self.Qstart = time.time()
# Clears last view
if self.summarySelected:
self.clearView()
self.createSumPlot("Summary")
self.socialNetWidget.reload()
# If a road network is selected, display info
if self.selectedRoadNetwork is not None:
self.selectedRoadNetwork.visualize(self.roadGraphWidget)
# If social network is selected, display clusters
if self.selectedSocialNetwork is not None:
self.ids, self.centers, sizes, relations, popSize = self.selectedSocialNetwork.getSummaryClusters(self.toolbar.clusterInput.textBox.text())
self.visualizeSummaryData(self.ids, self.centers, sizes, relations, popSize)
with open('nx.html', 'r') as f:
html = f.read()
self.socialNetWidget.setHtml(html)
self.plotQueryUser()
self.Qend = time.time()
self.__UpdateQueryTime()
def interactiveKdVisualNodes(self, tree, graph=nx.Graph()):
tempTitle = '<p>Number of hops: ' + str(tree["hops"]) + '</p><p>Distance: ' + str(tree["distance"]) + '</p><p>Common Keywords:</p><ol>'
for key in tree["keywords"]:
tempTitle += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
tempTitle += '</ol>'
if tree["satisfy"] == True:
graph.add_node(tree["user"], physics=False, label=str(tree["user"]), color='blue', size=15, title=tempTitle)
else:
graph.add_node(tree["user"], physics=False, label=str(tree["user"]), color='grey', size=15, title=tempTitle)
for c in list(tree["children"]):
self.interactiveKdVisualNodes(tree["children"][c], graph)
return graph
def interactiveCommunityVisualNodes(self, tree, graph=nx.Graph()):
tempTitle = '<p>Number of hops: ' + str(tree["hops"]) + '</p><p>Distance: ' + str(tree["distance"]) + '</p><p>Degree of Similarity:</p>' + str(tree["deg_sim"]) + '<p>Common Keywords:</p><ol>'
for key in tree["keywords"]:
tempTitle += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
tempTitle += '</ol>'
user_pos = self.communityUserPos[tree["user"]]
if tree["satisfy"] == True:
graph.add_node(tree["user"], x=user_pos["x"], y=user_pos["y"], physics=False, label=str(tree["user"]), color='blue', size=15, title=tempTitle)
else:
graph.add_node(tree["user"], x=user_pos["x"], y=user_pos["y"], physics=False, label=str(tree["user"]), color='grey', size=15, title=tempTitle)
for c in list(tree["children"]):
self.interactiveCommunityVisualNodes(tree["children"][c], graph)
return graph
def interactiveTimeVisualNodes(self, tree, previousUsers, graph=nx.Graph()):
tempTitle = '<p>Number of hops: ' + str(tree["hops"]) + '</p><p>Distance: ' + str(tree["distance"]) + '</p><p>Degree of Similarity:</p>' + str(tree["deg_sim"]) + '<p>Common Keywords:</p><ol>'
for key in tree["keywords"]:
tempTitle += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
tempTitle += '</ol>'
user_pos = self.communityUserPos[tree["user"]]
if tree["satisfy"] == True:
print(str(tree["user"]))
if str(tree["user"]) in previousUsers:
graph.add_node(tree["user"], x=user_pos["x"], y=user_pos["y"], physics=False, label=str(tree["user"]), color='#008cff', size=15, title=tempTitle)
else:
graph.add_node(tree["user"], x=user_pos["x"], y=user_pos["y"], physics=False, label=str(tree["user"]), color='blue', size=15, title=tempTitle)
else:
graph.add_node(tree["user"], x=user_pos["x"], y=user_pos["y"], physics=False, label=str(tree["user"]), color='grey', size=15, title=tempTitle)
for c in list(tree["children"]):
self.interactiveTimeVisualNodes(tree["children"][c], previousUsers, graph)
return graph
#def visualizeKdData(self, users, keys, hops, dists):
def visualizeKdData(self, kdTree):
if self.queryUser is not None:
"""
Interactive code has been moved to the KDTrust class
# Create Interactive Graph HTML File Using pyvis
network = nx.Graph()
titleTemp = '<p>Keywords:</p><ol>'
# Add query user
queryKeys = self.selectedSocialNetwork.getUserKeywords(self.queryUser[0])
for key in queryKeys:
titleTemp += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
titleTemp += '</ol>'
network.add_node(self.queryUser[0], physics=False, label=str('Query: ') + str(int(float(self.queryUser[0]))),
color='green', size=15, shape='star', title=titleTemp)
# Add common users
common = self.selectedSocialNetwork.userLoc(self.queryUser[0])
commonLoc = self.selectedRoadNetwork.findNearest(common)
for user in users:
query = self.selectedSocialNetwork.userLoc(user)
d = dists[user]
h = hops[user]
if h == -1:
h = 1
k = keys[user]
temp = '<p>Number of hops: ' + str(h) + '</p><p>Distance: ' + str(d) + '</p><p>Common Keywords:</p><ol>'
for key in k:
temp += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
temp += '</ol>'
if user != self.queryUser[0]:
network.add_node(user, physics=False, label=str(int(float(user))), color='blue', title=temp)
rels = self.selectedSocialNetwork.commonRelations(user, users)
for rel in rels:
network.add_edge(rel, user, color='blue')
"""
graph = self.interactiveKdVisualNodes(kdTree, graph=nx.Graph())
titleTemp = '<p>Keywords:</p><ol>'
# Add query user
queryKeys = self.selectedSocialNetwork.getUserKeywords(self.queryUser[0])
for key in queryKeys:
titleTemp += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
titleTemp += '</ol>'
graph.add_node(self.queryUser[0], physics=False, label=str('Query: ') + str(int(float(self.queryUser[0]))),
color='green', size=15, shape='star', title=titleTemp)
result_users, pass_users = self.treeUsers(kdTree, [], [])
all_users = set(result_users) | set(pass_users)
for u in all_users:
rels = self.selectedSocialNetwork.getUserRel(u)
rel_users = []
for r in rels:
rel_users.append(r[0])
relations = set(rel_users) & set(all_users)
for r in relations:
graph.add_edge(u, r, color='black')
nt = Network()
nt.from_nx(graph)
nt.set_options('{"layout": {"randomSeed":2}}')
nt.save_graph('kd-trust.html')
qu = self.queryUser[0]
self.clearView()
self.createSumPlot()
if self.selectedRoadNetwork:
self.selectedRoadNetwork.visualize(self.roadGraphWidget)
self.ids, self.centers, sizes, relations, popSize = self.selectedSocialNetwork.getSummaryClusters(self.toolbar.clusterInput.textBox.text())
self.visualizeSummaryData(self.ids, self.centers, sizes, relations, popSize)
self.setQueryUser(qu)
for user in result_users:
temp = self.selectedSocialNetwork.userLoc(user)
self.roadGraphWidget.plot([float(temp[0][0])], [float(temp[0][1])], pen=None, symbol='o', symbolSize=20,
symbolPen=(50, 50, 200, 25), symbolBrush=(50, 50, 200, 175))
#network.add_edge(self.queryUser[0], user, color='red')
self.plotQueryUser()
#nt = Network('100%', '100%')
#nt.from_nx(network)
#nt.save_graph('nx.html')
def updateKdSummaryGraph(self):
self.timeline.hide()
self.socialNetWidget.reload()
# If social network is selected, display clusters
if self.selectedSocialNetwork is not None:
#kd, keys, hops, dists = self.getKDTrust(self.__windows[6].kTextBox.text(), self.__windows[6].dTextBox.text(),
# self.__windows[6].eTextBox.text())
#self.visualizeKdData(kd, keys, hops, dists)
self.CTstart = time.time()
res = self.queryInput.getKdResponse()
kdTree = self.getKDTrust(res[0], res[1], res[2])
self.visualizeKdData(kdTree)
# Stop counting time for query
self.CTend = time.time()
self.__UpdateQueryTime()
with open('kd-trust.html', 'r') as f:
html = f.read()
self.socialNetWidget.setHtml(html)
def visualizeCommunityTimeData(self, kdTree):
if self.queryUser is not None:
if self.timeline.getFrame() == 0 or self.previousUsers == 1:
self.previousUsers = []
else:
self.previousUsers, previousPass = self.treeUsers(self.__queryFrames[self.timeline.getFrame() - 1], [], [])
graph = self.interactiveTimeVisualNodes(kdTree, self.previousUsers, graph=nx.Graph())
titleTemp = '<p>Keywords:</p><ol>'
# Add query user
queryKeys = self.selectedSocialNetwork.getUserKeywords(self.queryUser[0])
for key in queryKeys:
titleTemp += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
titleTemp += '</ol>'
query_pos = self.communityUserPos[self.queryUser[0]]
graph.add_node(self.queryUser[0], x=query_pos["x"], y=query_pos["y"], physics=False, label=str('Query: ') + str(int(float(self.queryUser[0]))),
color='green', size=15, shape='star', title=titleTemp)
result_users, pass_users = self.treeUsers(kdTree, [], [])
all_users = set(result_users) | set(pass_users)
for u in all_users:
rels = self.selectedSocialNetwork.getUserRel(u)
rel_users = []
for r in rels:
rel_users.append(r[0])
relations = set(rel_users) & set(all_users)
for r in relations:
graph.add_edge(u, r, color='black')
nt = Network()
nt.from_nx(graph)
nt.set_options('{"layout": {"randomSeed":2}}')
nt.save_graph('community-query.html')
qu = self.queryUser[0]
#self.clearView()
self.win.removeItem(self.roadGraphWidget)
self.roadGraphWidget = None
self.roadGraphWidget = self.win.addPlot(row=0, col=1, title="Community Query")
self.roadGraphWidget.clear()
if self.selectedRoadNetwork:
self.selectedRoadNetwork.visualize(self.roadGraphWidget)
#self.ids, self.centers, sizes, relations, popSize = self.selectedSocialNetwork.getSummaryClusters(self.clusterInput.textBox.text())
#self.visualizeSummaryData(self.ids, self.centers, sizes, relations, popSize)
x = []
y = []
for user in result_users:
user_location = self.selectedSocialNetwork.userLoc(user)
x.append(float(user_location[0][0]))
y.append(float(user_location[0][1]))
self.roadGraphWidget.plot(x, y, pen=None, symbol='o', symbolSize=10,
symbolPen=(50, 50, 200, 100), symbolBrush=(50, 50, 200, 175))
#self.setQueryUser(qu)
#network.add_edge(self.queryUser[0], user, color='red')
#self.plotQueryUser()
if self.queryUser is not None:
if not self.queryUserPlots:
[a.clear() for a in self.queryUserPlots]
self.queryUserPlots = []
color = 'green'
for loc in self.queryUser[1]:
self.queryUserPlots.append(self.roadGraphWidget.plot([float(loc[0])], [float(loc[1])], pen=None,
symbol='star', symbolSize=30, symbolPen=color,
symbolBrush=color))
def visualizeCommunityData(self, kdTree):
if self.queryUser is not None:
graph = self.interactiveCommunityVisualNodes(kdTree, graph=nx.Graph())
titleTemp = '<p>Keywords:</p><ol>'
# Add query user
queryKeys = self.selectedSocialNetwork.getUserKeywords(self.queryUser[0])
for key in queryKeys:
titleTemp += '<li>' + str(self.selectedSocialNetwork.getKeywordByID(key)) + '</li>'
titleTemp += '</ol>'
query_pos = self.communityUserPos[self.queryUser[0]]
graph.add_node(self.queryUser[0], x=query_pos["x"], y=query_pos["y"], physics=False, label=str('Query: ') + str(int(float(self.queryUser[0]))),
color='green', size=15, shape='star', title=titleTemp)
result_users, pass_users = self.treeUsers(kdTree, [], [])
all_users = set(result_users) | set(pass_users)
for u in all_users:
rels = self.selectedSocialNetwork.getUserRel(u)
rel_users = []
for r in rels:
rel_users.append(r[0])
relations = set(rel_users) & set(all_users)
for r in relations:
graph.add_edge(u, r, color='black')
nt = Network()
nt.from_nx(graph)
nt.set_options('{"layout": {"randomSeed":2}}')
nt.save_graph('community-query.html')
qu = self.queryUser[0]
#self.clearView()
self.win.removeItem(self.roadGraphWidget)
self.roadGraphWidget = None
self.roadGraphWidget = self.win.addPlot(row=0, col=1, title="Community Query")
self.roadGraphWidget.clear()
if self.selectedRoadNetwork:
self.selectedRoadNetwork.visualize(self.roadGraphWidget)
#self.ids, self.centers, sizes, relations, popSize = self.selectedSocialNetwork.getSummaryClusters(self.clusterInput.textBox.text())
#self.visualizeSummaryData(self.ids, self.centers, sizes, relations, popSize)
x = []
y = []
for user in result_users:
user_location = self.selectedSocialNetwork.userLoc(user)
x.append(float(user_location[0][0]))
y.append(float(user_location[0][1]))
self.roadGraphWidget.plot(x, y, pen=None, symbol='o', symbolSize=10,
symbolPen=(50, 50, 200, 100), symbolBrush=(50, 50, 200, 175))
#self.setQueryUser(qu)
#network.add_edge(self.queryUser[0], user, color='red')
#self.plotQueryUser()
if self.queryUser is not None:
if not self.queryUserPlots:
[a.clear() for a in self.queryUserPlots]
self.queryUserPlots = []
color = 'green'
for loc in self.queryUser[1]:
self.queryUserPlots.append(self.roadGraphWidget.plot([float(loc[0])], [float(loc[1])], pen=None,
symbol='star', symbolSize=30, symbolPen=color,
symbolBrush=color))
def updateCommunitySummaryGraph(self):
self.timeline.hide()
self.socialNetWidget.reload()
# If social network is selected, display clusters
if self.selectedSocialNetwork is not None:
queryKeywords = self.queryInput.getCommunityKeywords()
queryKeywords += self.selectedSocialNetwork.getUserKeywords(self.queryUser[0])
queryRelsRaw = self.selectedSocialNetwork.getUserRel(self.queryUser[0])
queryRels = []
for r in queryRelsRaw:
queryRels.append(r[0])
self.CTstart = time.time()
#community = self.communityTree(self.queryUser[0], queryKeywords, queryRels, float(self.__windows[6].kcTextBox.text()), float(self.__windows[6].kTextBox.text()), float(self.__windows[6].rTextBox.text()), float(self.__windows[6].dTextBox.text()), float(self.__windows[6].eTextBox.text()),[], 0, 0)
res = self.queryInput.getCommunityResponse()
community = self.communityTree(self.queryUser[0], queryKeywords, queryRels, float(res[0]), float(res[3]), float(res[4]), float(res[1]), float(res[2]), [], 0, 0)
community = self.pruneTree(community)
temp_users = self.treeUsers()
users = list(set(temp_users[0]) | set(temp_users[1]))
for user in users:
self.communityUserPos[user] = {
"x": random.randint(0, 350),
"y": random.randint(0, 350)
}
self.visualizeCommunityData(community)
# Stop counting time for query
self.CTend = time.time()
self.__UpdateQueryTime()
with open('community-query.html', 'r') as f:
html = f.read()
self.socialNetWidget.setHtml(html)
def timelineThread(self):
# self.socialNetWidget.reload()
if not self.playAnimation:
return
# frame = self.timeline.getFrame()+1
for frame in range(self.timeline.getFrame()+1, 11):
if self.playAnimation:
self.timeline.setFrame(frame)
QTimer.singleShot(0, self.updateTimeline) # Start the timer in the main thread
time.sleep(2)
else:
break
self.timeline.play.setText("Play")
def playTimeline(self):
self.playAnimation = not self.playAnimation
if self.playAnimation:
self.timeline_thread = threading.Thread(target=self.timelineThread)
self.timeline_thread.start()
self.timeline.play.setText("Pause" if self.playAnimation else "Play")
def updateTimeline(self):
# values = self.timeline.getDates()
# # convert from int to dates
# start = str(datetime.date(2020, 1, 1) + datetime.timedelta(days=values[0]))
# end = str(datetime.date(2020, 1, 1) + datetime.timedelta(days=values[1]))
#self.socialNetWidget.reload()
# If social network is selected, display clusters
if self.selectedSocialNetwork is not None:
frame = self.timeline.getFrame()
if frame == 0:
self.timeline.setDates("Start :" + str(self.query_dates[0].strftime('%m/%d/%Y')), "End :" + str(self.query_dates[10].strftime('%m/%d/%Y')))
else:
self.timeline.setDates("Start :" + str(self.query_dates[0].strftime('%m/%d/%Y')), "End :" + str(self.query_dates[frame].strftime('%m/%d/%Y')))
self.visualizeCommunityTimeData(self.__queryFrames[frame])
with open('community-query.html', 'r') as f:
html = f.read()
self.socialNetWidget.setHtml(html)
def get_evenly_spaced_dates(self, start_date, end_date, num_dates):
delta = (end_date - start_date) / (num_dates - 1)
dates = [start_date + i * delta for i in range(num_dates)]
return dates
def updateCommunityTimeSummaryGraph(self):
self.timeline.show()
self.socialNetWidget.reload()
# If social network is selected, display clusters
if self.selectedSocialNetwork is not None:
self.CTstart = time.time()
res = self.queryInput.getCommunityTimeResponse()
self.query_dates = self.get_evenly_spaced_dates(datetime.datetime.strptime(res[6], "%Y-%m-%d"), datetime.datetime.strptime(res[7], "%Y-%m-%d"), 11)
users = []
for i in range(0, len(self.query_dates)):
if i == 0:
queryKeywords = self.queryInput.getCommunityKeywords()
queryKeywords += self.selectedSocialNetwork.getUserKeywordsInTime(self.queryUser[0], res[6], res[7])
queryRelsRaw = self.selectedSocialNetwork.getUserRel(self.queryUser[0])
queryPois = self.selectedSocialNetwork.getUserPoiInTime(self.queryUser[0], res[6], res[7])
queryRels = []
for r in queryRelsRaw:
queryRels.append(r[0])
community = self.communityTimeTree(
self.queryUser[0],
queryKeywords,
queryRels,
queryPois,
res[6],
res[7],
float(res[0]),
float(res[3]),
float(res[4]),
float(res[5]),
float(res[1]),
float(res[2]),
[],
0,
0)
self.__queryFrames.append(self.pruneTree(community))
frame_users = self.treeUsers(community)
temp_users = list(set(frame_users[0]) | set(frame_users[1]))
users = list(set(users) | set(temp_users))
else:
date = str(self.query_dates[i-1])
queryKeywords = self.queryInput.getCommunityKeywords()
res = self.queryInput.getCommunityTimeResponse()
queryKeywords += self.selectedSocialNetwork.getUserKeywordsInTime(self.queryUser[0], res[6], date)
queryRelsRaw = self.selectedSocialNetwork.getUserRel(self.queryUser[0])
queryPois = self.selectedSocialNetwork.getUserPoiInTime(self.queryUser[0], res[6], date)
queryRels = []
for r in queryRelsRaw:
queryRels.append(r[0])
community = self.communityTimeTree(
self.queryUser[0],
queryKeywords,
queryRels,
queryPois,
res[6],
date,
float(res[0]),
float(res[3]),
float(res[4]),
float(res[5]),
float(res[1]),
float(res[2]),
[],
0,
0)
self.__queryFrames.append(self.pruneTree(community))
frame_users = self.treeUsers(community)
temp_users = list(set(frame_users[0]) | set(frame_users[1]))
users = list(set(users) | set(temp_users))
for user in users:
self.communityUserPos[user] = {
"x": random.randint(0, 500),
"y": random.randint(0, 500)
}
# self.visualizeCommunityData(self.__queryFrames[0])
# Stop counting time for query
self.CTend = time.time()
self.__UpdateQueryTime()
# with open('community-query.html', 'r') as f:
# html = f.read()
# self.socialNetWidget.setHtml(html)
self.updateTimeline()
#Generate kdtrust from input
def getKDTrust(self, keywords, hops, distance):
if self.queryUser is not None:
#kd = KDTrust(self.selectedRoadNetwork, self.selectedSocialNetwork, self.queryUser[0], float(keywords), float(distance), float(hops))
queryKeywords = self.selectedSocialNetwork.getUserKeywords(self.queryUser[0])
if float(distance) == 0.0:
distance = 9999.0
print(distance)
kdTree = self.kdTree(queryKeywords, self.queryUser[0], float(keywords), float(distance), float(hops), 0, 0, [])
kdTree = self.pruneTree(kdTree)
"""
# Users with common keywords
common, keys = self.usersCommonKeyword(k=float(keywords))
# Narrow query down to users within hops
common, hops = self.usersWithinHops(common, h=float(hops))
# Narrow down with degree of similarity distance (longest compute time)
common, dists = self.usersWithinDistance(common, d=float(distance))
neighbors = []
for user in common:
path = self.selectedSocialNetwork.shortestPath(self.queryUser[0], user)
print(path)
neighbors = list(set(neighbors) | set(path))
print(neighbors)
common = []
keys = []
hops = []
dists = []
users = kd.getUsers()
"""
return kdTree
def __UpdateQueryTime(self):
self.SummaryResponseTime = (self.Qend - self.Qstart) * 1000
self.ClusterResponseTime = (self.CTend - self.CTstart) * 1000
self.__ViewStats()
# Returns query user in form [id, [[lat, lon], [lat, lon]]]
def setQueryUser(self, user, window=4):
if self.queryUser is not None:
[a.clear() for a in self.queryUserPlots]
self.queryUserPlots = []
self.queryUser = self.selectedSocialNetwork.getUser(user)
self.plotQueryUser()
self.queryUserToolbar.userLabel.setText(user.split(".0")[0])
#self.usersCommonKeyword()
self.__windows[window].close()
self.dijkstra(self.queryUser)
def plotQueryUser(self):
if self.queryUser is not None:
if not self.queryUserPlots:
[a.clear() for a in self.queryUserPlots]
self.queryUserPlots = []
color = 'green'
for loc in self.queryUser[1]:
if self.summarySelected:
self.clearView()
self.plottingUserRefresh()
self.queryUserPlots.append(self.roadGraphWidget.plot([float(loc[0])], [float(loc[1])], pen=None,
symbol='star', symbolSize=30, symbolPen=color,
symbolBrush=color))
def plottingUserRefresh(self):
self.createSumPlot("Summary")
self.socialNetWidget.reload()
if self.selectedRoadNetwork is not None:
self.selectedRoadNetwork.visualize(self.roadGraphWidget)
# If social network is selected, display clusters
if self.selectedSocialNetwork is not None:
self.ids, self.centers, sizes, relations, popSize = self.selectedSocialNetwork.getSummaryClusters(
self.toolbar.clusterInput.textBox.text())
self.visualizeSummaryData(self.ids, self.centers, sizes, relations, popSize)
with open('nx.html', 'r') as f:
html = f.read()
self.socialNetWidget.setHtml(html)
def setQueryKeyword(self, keyword):
self.queryKeyword = keyword
self.queryUserToolbar.keywordLabel.setText(self.selectedSocialNetwork.getKeywordByID(keyword))
self.__windows[5].close()
# Display for loading networks
def viewFiles(self):
# Set up hierarchy base
self.__fileTreeObjects = {
'0': QtWidgets.QTreeWidgetItem(["Road Networks"]),
'1': QtWidgets.QTreeWidgetItem(["Social Networks"])
}
# Set up tree widget
self.__windows[0] = pg.TreeWidget()
self.__windows[0].setWindowModality(QtCore.Qt.ApplicationModal)
self.__windows[0].setDragEnabled(False)
self.__windows[0].header().setSectionsMovable(False)
self.__windows[0].header().setStretchLastSection(False)
self.__windows[0].header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
self.__windows[0].setWindowTitle('Network Files')
self.__windows[0].setColumnCount(2)
self.__windows[0].resize(int(self.frameGeometry().width() / 3), int(self.frameGeometry().height() / 3))
# Show TreeWidget
self.__windows[0].show()
# Add Road Networks and Social Networks to hierarchy
self.__windows[0].addTopLevelItem(self.__fileTreeObjects['0'])
self.__windows[0].addTopLevelItem(self.__fileTreeObjects['1'])
# Add button to add a new Road Network
nrn = QtWidgets.QPushButton("New Road Network")
nrn.clicked.connect(lambda: self.newNetwork("road"))
self.__windows[0].setItemWidget(self.__fileTreeObjects['0'], 1, nrn)
# Add button to add a new Social Network
nsn = QtWidgets.QPushButton("New Social Network")
nsn.clicked.connect(lambda: self.newNetwork("social"))
self.__windows[0].setItemWidget(self.__fileTreeObjects['1'], 1, nsn)
# Adds all sub-objects to roadNetworks. Each element is given a number in order for the hierarchy. For example,
# 1.3 is the fourth child of the second element
i = 0
for x in self.__roadNetworks:
i += 1
self.__fileTreeObjects[f"0.{i}"] = QtWidgets.QTreeWidgetItem([x])
self.__fileTreeObjects['0'].addChild(self.__fileTreeObjects[f"0.{i}"])
j = 0
# Adds files
cFile = {}
for y in self.__roadNetworks[x]:
j += 1
iName = self.__roadNetworks[x][y]
if iName != f"[{iName}]":
iNameArr = iName.split("/")
iName = iNameArr[len(iNameArr) - 1]
self.__fileTreeObjects[f"0.{i}.{j}"] = QtWidgets.QTreeWidgetItem([iName])
self.__fileTreeObjects[f"0.{i}"].addChild(self.__fileTreeObjects[f"0.{i}.{j}"])
cFile[j] = QtWidgets.QPushButton("Choose File")
cFile[j].clicked.connect(
lambda junk, a=i, d=j, b=x, c=y: self.chooseFile(f"0.{a}.{d}", "Road Network", b, c))
self.__windows[0].setItemWidget(self.__fileTreeObjects[f"0.{i}.{j}"], 1, cFile[j])
# Adds all sub-objects to socialNetworks. Each element is given a number in order for the hierarchy. For
# example, 1.3 is the fourth child of the second element
i = 0
cFileS = {}
for x in self.__socialNetworks:
i += 1
self.__fileTreeObjects[f"1.{i}"] = QtWidgets.QTreeWidgetItem([x])
self.__fileTreeObjects['1'].addChild(self.__fileTreeObjects[f"1.{i}"])
j = 0
# Adds files
for y in self.__socialNetworks[x]:
j += 1
iName = self.__socialNetworks[x][y]
if iName != f"[{iName}]":
iNameArr = iName.split("/")
iName = iNameArr[len(iNameArr) - 1]
self.__fileTreeObjects[f"1.{i}.{j}"] = QtWidgets.QTreeWidgetItem([iName])
self.__fileTreeObjects[f"1.{i}"].addChild(self.__fileTreeObjects[f"1.{i}.{j}"])
cFileS[f"{j}.{j}"] = QtWidgets.QPushButton("Choose File")
cFileS[f"{j}.{j}"].clicked.connect(
lambda junk, a=i, b=j, c=x, d=y: self.chooseFile(f"1.{a}.{b}", "Social Network", c, d))
self.__windows[0].setItemWidget(self.__fileTreeObjects[f"1.{i}.{j}"], 1, cFileS[f"{j}.{j}"])
# TODO: Fix issue where networks aren't loaded after they are created -- program requires restart
# Creates a new Road network
def newNetwork(self, type):
if type != "road" and type != "social":
print("ERROR: newNetwork() must have type road or social")
exit(0)
title = ""
network = None
num = -1
if type == "road":
title = "Road Network"
network = self.__roadNetworks
num = 0
elif type == "social":
title = "Social Network"
num = 1
network = self.__socialNetworks
self.__windows[1] = QtWidgets.QInputDialog()
text, ok = self.__windows[1].getText(self, f'New {title}', f"Enter your {title.lower()} name:")
text = str(text)
# If the road network does not exist already, add it to the config
if ok and text not in network.keys() and text != "":
if type == "road":
network[text] = {
"nodeFile": "[nodeFile]",
"edgeFile": "[edgeFile]",
"POIFile": "[POIFile]",