-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteract.py
1716 lines (1536 loc) · 64.9 KB
/
interact.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
# -*- coding: utf-8 -*-
# @Time : 2018/7/15 14:07
# @Author : SilverMaple
# @Site : https://github.com/SilverMaple
# @File : interact.py
# import warnings
# warnings.simplefilter("error")
import shutil
from threading import _start_new_thread
from PIL import Image
from visualization import Network, Community, COMMUNITY_FILE, NETWORK_FILE, MUTUAL_INFORMATION_FILE, COLOR_CONFIG, SHAPE_CONFIG
from FR import FRLayout, FR3DLayout
from KK import KKLayout
import sys
import os
from PyQt5.QtCore import Qt, QLineF, QRectF, QPoint, QThread, pyqtSignal, QSize
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QGraphicsView, QGraphicsScene, QGridLayout, \
QMessageBox, QWidget, QPushButton, QGraphicsLineItem, QLabel, QAction, QShortcut, QInputDialog, QLineEdit, \
QFileDialog
from PyQt5.QtGui import QPainter, QPen, QColor, QCursor, QMouseEvent, QIcon, QKeySequence, QPalette, QBrush, QPixmap, \
QFont, QImage
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import matplotlib.pyplot as plt
import numpy as np
POINT_SIZE = 10
# POINT_SIZE = 10
APP_WIDTH = 1320
APP_HEIGHT = 500
ICON_PATH = 'c_plus/select.ico'
UNIFIED_FONT_SIZE = 10
UNIFIED_FONT = QFont("SimSun", UNIFIED_FONT_SIZE)
LABEL_FONT = QFont("Times New Roman", 12)
LABEL_PADDING = 8
# oringinal style sheet
'''
QPushButton{
background-color: %s ;
border-style: outset;
border-width: 1px;
border-radius: 5px;
border-color: black;
font: 1px;
padding: 0px;
}
QPushButton:hover {
background-color: %s;
border-style: inset;
}
QPushButton:pressed {
background-color: rgb(224, 0, 0);
border-style: inset;
}
QPushButton#cancel{
background-color: red ;
}
'''
CSS_BUTTON_STYLE_SHEET_DELETE = '''
QPushButton{
background-color: %s ;
border-style: outset;
border-width: 0px;
border-radius: 5px;
border-color: black;
font: 1px;
padding: 0px;
background-color: rgb(0, 0, 0, 0);
}
QPushButton:hover {
border-width: 1px;
background-color: %s;
border-style: inset;
}
QPushButton:pressed {
background-color: rgb(224, 0, 0, 0);
border-style: inset;
}
'''
CSS_BUTTON_STYLE_SHEET_MID = CSS_BUTTON_STYLE_SHEET_DELETE%('%s', 'rgb(0, 0, 0, 0);border-width: 0px')
CSS_BUTTON_STYLE_SHEET = CSS_BUTTON_STYLE_SHEET_DELETE%('%s', 'yellow')
class Point:
def __init__(self, x, y, name, color=None):
self.x = x
self.y = y
self.name = name
self.color = color
self.display = True
class Line:
def __init__(self, a, b, color_index, color=None):
self.a = a
self.b = b
self.color_index = color_index
self.color = color
self.display = True
class IconManager():
def __init__(self):
pass
def generateIcon(self, colorDict=None):
colorDict = {'red': 5, 'blue': 2, 'green': 3}
# data = np.random.randint(1, 11, 5)
plt.pie(colorDict.values(), colors=colorDict.keys())
plt.axis('equal')
plt.axis('off')
fig = plt.gcf()
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.margins(0,0)
# fig.savefig('a.png', format='png', transparent=True, dpi=10, pad_inches = 0)
# plt.savefig('a.svg', dpi=10, pad_inches=0, transparent=True)
def getIcon(self, index):
pass
class Messenger:
def __init__(self):
self.setupFlag = False
self.statusBar = None
def setup(self, statusBar):
self.statusBar = statusBar
self.setupFlag = True
def changeStatusBar(self, content):
try:
if self.setupFlag:
self.statusBar.showMessage(content)
except Exception as e:
print(e)
messenger = Messenger()
class ActionButton(QPushButton):
def __init__(self, ci, index, ofCommunity, *__args):
super().__init__(*__args)
self.ci = ci
self.index = index
self.ofCommunity = ofCommunity
def mousePressEvent(self, event):
ci = self.ci
print('changeCommunity: ', ci)
if ci == self.ofCommunity:
return
else:
tempCommunity = {'index': self.index, 'from': self.ofCommunity, 'to': ci}
vpResultView.updateEntropy(community=tempCommunity)
class PointButton(QPushButton):
def __init__(self, ig, index, color, *args):
QPushButton.__init__(self, *args)
self.setMouseTracking(True)
self.setStyleSheet((CSS_BUTTON_STYLE_SHEET) % color)
self.color = color
self.changeColor = None
self.ig = ig
self.index = index
self.x = self.ig.points[index].x
self.y = self.ig.points[index].y
self.dragging = False
self.ofCommunity = None
self.raise_()
for ci in range(len(self.ig.network.communities)):
if index+1 in self.ig.network.communities[ci].vertexes:
self.ofCommunity = ci
break
self.selectedCommunity = self.ofCommunity
self.setContextMenuPolicy(Qt.ActionsContextMenu)
# self.customContextMenuRequested.connect(self.showContextMenu)
self.contextMenu = QMenu(self)
# self.contextMenu.addSection()
# self.communityMenu = self.contextMenu.addMenu('移动至社区')
for ci in range(len(self.ig.network.communities)):
tempAction = self.contextMenu.addAction("社区%d" % (ci+1))
tempAction.triggered.connect(lambda: self.changeCommunity(ci))
self.contextMenuState = False
def changeCommunity(self, ci):
# 直接使用坐标计算选择社区,以后有修改方法后再改
ci = int(((QCursor.pos().y() - self.menuPos.y())-2) / 23)
if ci == self.selectedCommunity:
return
# elif ci == self.ofCommunity:
# self.changeColor = None
# self.restore()
# self.ig.points[self.index].display = True
# self.update()
# print('here')
# tempCommunity = {'index': self.index, 'from': self.ofCommunity, 'to': ci}
# vpResultView.updateEntropy(community=tempCommunity)
else:
self.selectedCommunity = ci
self.changeColor = self.ig.colors[ci]
self.setStyleSheet((CSS_BUTTON_STYLE_SHEET) % self.changeColor)
for line in vLineScene.lineItem:
anotherPoint = None
if line.a == self.index+1:
anotherPoint = line.b
elif line.b == self.index+1:
anotherPoint = line.a
else:
continue
if self.ig.points[anotherPoint-1].color == self.changeColor:
line.setColor(self.changeColor)
line.changeColor = self.changeColor
else:
line.setColor('#000000')
line.changeColor = '#000000'
if ci == self.ofCommunity:
self.changeColor = None
self.update()
tempCommunity = {'index': self.index, 'from': self.ofCommunity, 'to': ci}
vpResultView.updateEntropy(community=tempCommunity)
def showContextMenu(self, pos):
self.menuPos = QCursor.pos()
# 菜单显示前,将它移动到鼠标点击的位置
for i in range(len(self.contextMenu.actions())):
if self.selectedCommunity == i:
self.contextMenu.actions()[i].setIconText('✔')
self.contextMenu.actions()[i].setIcon(QIcon(ICON_PATH))
self.contextMenu.actions()[i].setIconVisibleInMenu(True)
else:
self.contextMenu.actions()[i].setIconText('')
self.contextMenu.actions()[i].setIconVisibleInMenu(False)
self.contextMenu.exec(QCursor.pos()) # 在鼠标位置显示
# self.contextMenu.show()
def restore(self, saveColor=None):
if not saveColor and self.changeColor:
self.changeColor = None
self.setStyleSheet((CSS_BUTTON_STYLE_SHEET) % self.color)
self.resize(10, 10)
self.setWindowOpacity(1)
def mouseMoveEvent(self, event):
if self.dragging:
message = 'move event at point[ ' + str(self.index+1) + ' ]: ' + str(event.pos().x()) + ' ' + str(event.pos().y())
x = self.pos().x() + event.pos().x()
y = self.pos().y() + event.pos().y()
self.ig.points[self.index].x = x
self.ig.points[self.index].y = y
self.move(x, y)
vLineScene.buttonLabels[self.index].move(x+LABEL_PADDING, y+LABEL_PADDING)
# self.ig.vpViews[2].buttonLabels[self.index].move(x, y)
for l in vLineScene.lineItem:
if l.a == self.index+1 or l.b == self.index+1:
x = self.ig.points[l.a - 1].x + POINT_SIZE / 2
y = self.ig.points[l.a - 1].y + POINT_SIZE / 2
x1 = self.ig.points[l.b - 1].x + POINT_SIZE / 2
y1 = self.ig.points[l.b - 1].y + POINT_SIZE / 2
# 设置直线位于(x1, y1)和(x2, y2)之间
l.setLine(QLineF(x, y, x1, y1))
# vLineView.update()
vpFrontView.update()
messenger.changeStatusBar(message)
def mouseReleaseEvent(self, event):
message = 'release event at point[ ' + self.text() + ' ]: ' + str(event.pos().x()) + ' ' + str(event.pos().y())
if event.pos().x() < 10 and event.pos().x() > 0 and event.pos().y() < 10 and event.pos().y() > 0:
return
x = self.pos().x() + event.pos().x()
y = self.pos().y() + event.pos().y()
self.dragging = False
# v, index = self.text()
# print(self.accessibleName())
# v, index = self.accessibleName()
messenger.changeStatusBar(message)
def dragMoveEvent(self, event):
message = 'drag move at point[ ' + self.text() + ' ]: ' + str(event.pos().x()) + ' ' + str(event.pos().y())
print(message)
messenger.changeStatusBar(message)
def dragLeaveEvent(self, event):
message = 'drag leave at point[ ' + self.text() + ' ]: ' + str(event.pos().x()) + ' ' + str(event.pos().y())
print(message)
messenger.changeStatusBar(message)
def mousePressEvent(self, event):
if Qt.MiddleButton == event.button():
# self.setStyleSheet((CSS_BUTTON_STYLE_SHEET_DELETE) % (self.color, self.color))
self.setStyleSheet((CSS_BUTTON_STYLE_SHEET_MID) % (self.color))
self.leaveEvent(event)
vpResultView.updateEntropy(dot=self.index)
message = 'press at point[ ' + self.text() + ' ]: ' + str(event.pos().x()) + ' ' + str(event.pos().y())
# print('press at point[ ', self.text(), ' ]: ', event.pos().x(), event.pos().y())
self.ig.points[self.index].display = False
self.hide()
print(self.windowState())
vLineScene.buttonLabels[self.index].hide()
vLineScene.leavePoint()
vLineScene.updateScene()
vpFrontView.update()
messenger.changeStatusBar(message)
elif Qt.RightButton == event.button():
self.showContextMenu(event.pos())
elif Qt.LeftButton == event.button():
self.dragging = True
def enterEvent(self, *args, **kwargs):
if self.changeColor:
self.setStyleSheet((CSS_BUTTON_STYLE_SHEET) % self.changeColor)
else:
self.setStyleSheet((CSS_BUTTON_STYLE_SHEET) % self.color)
inLineSum = 0
outLineSum = 0
regionCount = {c: 0 for c in self.ig.colors}
for i in range(len(self.ig.lines)):
if self.ig.lines[i].display and \
(self.ig.lines[i].a == self.index+1 or self.ig.lines[i].b == self.index+1):
if vLineScene.lineItem[i].getCurrentColor() == self.getCurrentColor():
inLineSum += 1
else:
outLineSum += 1
if self.ig.lines[i].a == self.index + 1:
anotherPoint = self.ig.lines[i].b
else:
anotherPoint = self.ig.lines[i].a
color = vLineScene.buttons[anotherPoint - 1].getCurrentColor()
regionCount[color] += 1
regionCount = {c: regionCount[c] for c in regionCount if regionCount[c] != 0}
regionString = '\n' + '\n'.join([' Community {}: {}'.format(self.ig.colors.index(c)+1, regionCount[c])
for c in regionCount])
self.setToolTip('Point: ' + str(self.index+1) + '\nInside: ' + str(inLineSum) +
'\nOutside: ' + str(outLineSum) + regionString)
message = 'Enter in point: ' + str(self.index + 1) + \
' InLine sum: ' + str(inLineSum) + ' OutLine sum: ' + str(outLineSum) + regionString.replace('\n', '')
vLineScene.focusPoint(self.index)
messenger.changeStatusBar(message)
def leaveEvent(self, *args, **kwargs):
message = 'Leave in point: ' + str(self.index + 1)
self.dragging = False
vLineScene.leavePoint(saveColor=True)
messenger.changeStatusBar(message)
def getCurrentColor(self):
if self.changeColor is None:
return self.color
return self.changeColor
def getGlobalPos(self):
return self.mapToParent(self.pos())
# return self.mapToGlobal(self.pos())
class LineItem(QGraphicsLineItem):
def __init__(self, ig, index, color, view, *args, **kwargs):
# QGraphicsLineItem.__init__(*args, **kwargs)
super().__init__(*args)
self.ig = ig
self.index = index
self.view = view
self.a = self.ig.lines[index].a
self.b = self.ig.lines[index].b
self.name = '-'.join([str(self.a), str(self.b)])
self.color = color
self.changeColor = None
self.width = 1
self.focus_opacity = 1
self.normal_opacity = 0.3
self.ignore_opacity = 0.1
self.setOpacity(self.normal_opacity)
self.setZValue(-1)
# 设置画笔
pen = self.pen()
p = QPen()
pen.setColor(QColor(self.color))
# print(self.color, self.width)
pen.setWidth(self.width)
self.setPen(pen)
self.setAcceptHoverEvents(True)
self.setAcceptTouchEvents(True)
self.setToolTip(self.name)
def setColor(self, color):
pen = self.pen()
p = QPen()
pen.setColor(QColor(color))
self.setPen(pen)
self.update()
def getCurrentColor(self):
if self.changeColor is None:
return self.color
return self.changeColor
def focus(self):
pen = self.pen()
pen.setWidth(2)
self.setPen(pen)
self.update()
def restore(self, saveColor=None):
self.setOpacity(self.normal_opacity)
pen = self.pen()
if not saveColor:
self.changeColor = None
pen.setColor(QColor(self.color))
pen.setWidth(self.width)
self.setPen(pen)
self.update()
def mousePressEvent(self, *args, **kwargs):
self.hoverLeaveEvent(*args, **kwargs)
vpResultView.updateEntropy(pair=(self.a, self.b))
self.ig.lines[self.index].display = False
print(self.isVisible())
self.hide()
print(self.isVisible())
self.view.update()
vpFrontView.update()
vpResultView.update()
print(self.isVisible())
messenger.changeStatusBar('mousePress for:%s' % self.name)
def hoverEnterEvent(self, *args, **kwargs):
pen = self.pen()
pen.setColor(QColor(Qt.yellow))
self.setPen(pen)
self.view.update()
messenger.changeStatusBar('hoverEnter for:%s' % self.name)
def hoverLeaveEvent(self, *args, **kwargs):
pen = self.pen()
if self.changeColor:
pen.setColor(QColor(self.changeColor))
else:
pen.setColor(QColor(self.color))
self.setPen(pen)
self.view.update()
messenger.changeStatusBar('hoverLeave for:%s' % self.name)
class ResultPainter(QWidget):
def __init__(self, ig, *args):
super().__init__(*args)
self.ig = ig
self.entropy = None
self.trigger = False
self.descLabel = None
self.isRemoveDots = False
self.isRemovePairs = False
self.isChangeCommunity = False
self.dots = []
self.pairs = []
self.changeSets = []
self.communities = []
self.initUI()
def initUI(self):
self.resize(300, 500)
self.hide()
self.descLabel = QLabel(self)
self.descLabel.setGeometry(20, 380, 260, 400)
self.descLabel.setFont(UNIFIED_FONT)
self.descLabel.setText("说明:\n"
" 鼠标悬停在点上的时候,第一个数字表示该节点的标识,第二个数字表示该节点与社区内节点的链接数目,"
"第三个数字表示该节点与其他社区节点的链接数目。"
"比如:59,6,4表示节点59与社区内节点的链接数目为6,与社区间其他节点的链接数目为4。")
self.descLabel.setWordWrap(True)
self.descLabel.setAlignment(Qt.AlignTop)
self.descLabel.show()
self.entropy = self.ig.network.get_entropy()
self.staticEntropy = self.entropy
for i in range(len(self.entropy)):
self.entropy[i] = float(self.entropy[i].replace('\n', ''))
def updateEntropy(self, pair=None, community=None, dot=None):
tempPair = None
tempCommunity = None
tempDot = None
print('----------------Update entropy----------------')
# 删除边
if pair is not None:
self.isRemovePairs = True
self.pairs.append(pair)
tempPair = self.pairs
if self.dots != []:
tempDot = self.dots
# 删除点和与其相连的边
if dot is not None:
dot += 1
self.isRemoveDots = True
for i in self.ig.lines:
if dot == i.a or dot == i.b:
self.pairs.append((i.a, i.b))
tempPair = self.pairs
self.dots.append(dot)
tempDot = self.dots
self.communities = []
# 删除点需重写社区划分信息
if tempDot is not None:
index = 0
# self.communities = []
if self.isChangeCommunity and community is None:
fromIndex = []
toIndex = []
pointIndex = []
for c in self.changeSets:
fromIndex.append(c['from'])
toIndex.append(c['to'])
pointIndex.append(c['index'])
# 如果未修改过社区划分信息,则重新赋值
if self.communities == []:
index = 0
for c in self.ig.network.communities:
self.communities.append([])
for v in c.vertexes:
self.communities[index].append(v)
index += 1
for index in range(len(pointIndex)):
print('move point %d from community %d to community %d'
% (pointIndex[index] + 1, fromIndex[index], toIndex[index]))
self.communities[fromIndex[index]].remove(pointIndex[index] + 1)
self.communities[toIndex[index]].append(pointIndex[index] + 1)
for j in range(len(self.communities)):
for v in self.communities[j]:
if v in tempDot:
self.communities[j].remove(v)
print('remove point: ', v)
index += 1
else:
for c in self.ig.network.communities:
self.communities.append([])
for v in c.vertexes:
if v not in tempDot:
self.communities[index].append(v)
else:
print('remove point: ', v)
index += 1
# remove empty array
while [] in self.communities:
self.communities.remove([])
tempCommunity = []
for c in self.communities:
tempCommunity.append(' '.join([str(i) for i in c]))
if tempCommunity == []:
tempCommunity = None
if community is not None:
if pair is None and self.pairs != []:
tempPair = self.pairs
if dot is None and self.dots != []:
for i in self.dots:
print('remove point:', i)
self.isChangeCommunity = True
# 注意同一个点不应该重复移动
removeItem = None
for i in self.changeSets:
# print(i['index'], community['index'])
if i['index'] == community['index']:
removeItem = i
break
if removeItem is not None:
# print('remove duplicate item')
self.changeSets.remove(removeItem)
self.changeSets.append(community)
fromIndex = []
toIndex = []
pointIndex = []
for c in self.changeSets:
fromIndex.append(c['from'])
toIndex.append(c['to'])
pointIndex.append(c['index'])
# 如果未修改过社区划分信息,则重新赋值
if self.communities == []:
index = 0
for c in self.ig.network.communities:
self.communities.append([])
for v in c.vertexes:
if self.dots == [] or self.dots != [] and v not in self.dots:
self.communities[index].append(v)
index += 1
for index in range(len(pointIndex)):
if self.dots != [] and pointIndex[index]+1 in self.dots:
continue
print('move point %d from community %d to community %d'
% (pointIndex[index]+1, fromIndex[index], toIndex[index]))
self.communities[fromIndex[index]].remove(pointIndex[index]+1)
self.communities[toIndex[index]].append(pointIndex[index]+1)
tempCommunity = []
for c in self.communities:
tempCommunity.append(' '.join([str(i) for i in c]))
# print('tempPair', tempPair)
# print('tempDot', tempDot)
# print('tempCommunity', tempCommunity)
# 获取原始信息熵
if not self.isRemovePairs and not self.isRemoveDots and not self.isChangeCommunity:
self.dots = []
self.pairs = []
self.changeSets = []
self.communities = []
self.entropy = self.staticEntropy
self.entropy = self.ig.network.get_entropy()
else:
self.entropy = self.ig.network.get_entropy(pair=tempPair, community=tempCommunity, dot=tempDot)
for i in range(len(self.entropy)):
self.entropy[i] = float(str(self.entropy[i]).replace('\n', ''))
print(['社区%d: %f'%(i+1, self.entropy[i]) for i in range(len(self.entropy))])
self.update()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.draw(qp)
qp.end()
def triggerUpdate(self):
self.trigger = True
def draw(self, qp):
index = 0
qp.setFont(UNIFIED_FONT)
for i in range(len(self.entropy)):
try:
pen = QPen(QColor(self.ig.colors[i]), 1, QtCore.Qt.SolidLine)
except Exception as e:
print(e)
print(i, len(self.entropy), len(self.ig.colors))
print(self.ig.colors)
qp.setPen(pen)
# qp.drawText(5, index * 20 + 20, "●")
# qp.drawText(20, index * 20 + (len(self.entropy)+8)*20, "●"+'代表社区%d'%(index+1))
img = QImage('c_plus/%s.png'%(SHAPE_CONFIG[i])).scaled(QSize(15, 15), Qt.IgnoreAspectRatio)
# 显示形状
qp.drawImage(20, (index-.8) * 20 * (UNIFIED_FONT_SIZE/12) + 40, img)
qp.drawText(40, index * 20 * (UNIFIED_FONT_SIZE/12) + 40, '代表社区%d'%(index+1))
# 只显示颜色不显示形状
# qp.drawText(20, index * 20 * (UNIFIED_FONT_SIZE/12) + 40, "●"+'代表社区%d'%(index+1))
pen = QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)
qp.setPen(pen)
# qp.drawText(20, index * 20 + 20,
# '{:<10}{}'.format('社区%d的H(X|Y)值:'%(index + 1), '%.6f'%(self.entropy[i])))
# '{:<10}{}'.format('社区%d的信息熵:'%(index + 1), '%.6f'%(self.entropy[i])))
index += 1
if ig.formulaState:
qp.drawText(20, 20, '{:<10}{}'.format('网络中的H(X|Y)值:', '%.6f'%(sum([i for i in self.entropy]))))
else:
Q = ig.getQ(len(ig.network.communities))
qp.drawText(20, 20, '{:<10}{}'.format('网络中的平均互信息值:', '%s' % (Q if Q is not None else '')))
# qp.drawText(20, (index + 1) * 20, '{:<10}{}'.format('H(X|Y)值的总和:', '%.6f'%(sum([i for i in self.entropy]))))
# qp.drawText(20, (index + 1) * 20, '{:<10}{}'.format('信息熵的总和:', '%.6f'%(sum([i for i in self.entropy]))))
self.descLabel.setGeometry(20, (index + 2) * 20 * (UNIFIED_FONT_SIZE/12), 260, 400)
if self.trigger:
qp.drawText(15, 200, "输出:%f" % sum([i for i in self.entropy]))
class NetworkView(QGraphicsView):
def __init__(self, *__args):
super().__init__(*__args)
self.m_translateButton = Qt.LeftButton
self.m_scale = 1.0
self.m_zoomDelta = 0.1
self.m_translateSpeed = 2.0
self.m_bMouseTranslate = False
self.m_lastMousePos = None
self.setRenderHint(QPainter.Antialiasing)
self.setSceneRect(0, 0, 500, 500)
self.centerOn(0, 0)
# 平移速度
def setTranslateSpeed(self, speed):
# 建议速度范围
assert speed >= 0.0 and speed <= 2.0, "self.setTranslateSpeed: Speed should be in range [0.0, 2.0]."
self.m_translateSpeed = speed
def translateSpeed(self):
return self.m_translateSpeed
# 缩放的增量
def setZoomDelta(self, delta):
# 建议增量范围
assert delta >= 0.0 and delta <= 1.0, "self.setZoomDelta: Delta should be in range [0.0, 1.0]."
self.m_zoomDelta = delta
def zoomDelta(self):
return self.m_zoomDelta
# 上 / 下 / 左 / 右键向各个方向移动、加 / 减键进行缩放、空格 / 回车键旋转
def keyPressEvent(self, event):
messenger.changeStatusBar('Key pressed: %s' % event.key())
# 使用==不能用is,因为类型不同值相同
if event.key() == Qt.Key_Up:
self.translate(0, -2) # 上移
elif event.key() == Qt.Key_Down:
self.translate(0, 2) # 下移
elif event.key() == Qt.Key_Left:
self.translate(-2, 0) # 左移
elif event.key() == Qt.Key_Right:
self.translate(2, 0) # 右移
elif event.key() == Qt.Key_Plus:
self.zoomIn() # 放大
elif event.key() == Qt.Key_Minus:
self.zoomOut() # 缩小
elif event.key() == Qt.Key_Space:
self.rotate(-5) # 逆时针旋转
elif event.key() == Qt.Key_Enter \
or event.key() == Qt.Key_Return:
self.rotate(5)
else:
super().keyPressEvent(event)
# 平移
def mouseMoveEvent(self, event):
messenger.changeStatusBar('Mouse move: %s' % str(event.pos()))
if self.m_bMouseTranslate:
mouseDelta = self.mapToScene(event.pos()) - self.mapToScene(self.m_lastMousePos)
self.translate(mouseDelta.x(), mouseDelta.y())
self.m_lastMousePos = event.pos()
super().mouseMoveEvent(event)
def mousePressEvent(self, event):
messenger.changeStatusBar('Mouse press: %s' % str(event.pos()))
if event.button() == self.m_translateButton:
# 当光标底下没有item时,才能移动
point = self.mapToScene(event.pos())
if self.scene().itemAt(point, self.transform()) is None:
self.m_bMouseTranslate = True
self.m_lastMousePos = event.pos()
super().mousePressEvent(event)
def mouseReleaseEvent(self, event):
messenger.changeStatusBar('Mouse release: %s' % str(event.pos()))
if event.button() == self.m_translateButton:
self.m_bMouseTranslate = False
super().mouseReleaseEvent(event)
# 放大 / 缩小
def wheelEvent(self, event):
# 滚轮的滚动量
scrollAmount = event.angleDelta()
# 正值表示滚轮远离使用者(放大),负值表示朝向使用者(缩小)
if scrollAmount.y() > 0:
self.zoomIn()
messenger.changeStatusBar('Zoom in: %s' % str(self.m_zoomDelta))
else:
self.zoomOut()
messenger.changeStatusBar('Zoom out: %s' % str(self.m_zoomDelta))
# 放大
def zoomIn(self):
self.zoom(1 + self.m_zoomDelta)
# 缩小
def zoomOut(self):
self.zoom(1 - self.m_zoomDelta)
# 缩放 - scaleFactor:缩放的比例因子
def zoom(self, scaleFactor):
# 防止过小或过大
factor = self.transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width()
if factor < 0.07 or factor > 100:
return
self.scale(scaleFactor, scaleFactor)
self.m_scale *= scaleFactor
# 缩放,可有可无
# if self.m_scale > 1:
# try:
# for i in vLineScene.buttons:
# i.resize(10-(self.m_scale-1)/2, 10-(self.m_scale-1)/2)
# i.move(i.x + self.m_scale/4, i.y + self.m_scale/4)
# except Exception as e:
# print(e)
# 平移
def translate(self, x, y):
messenger.changeStatusBar('Translate: %s' % str((x, y)))
delta = QPoint(x, y)
# 根据当前zoom缩放平移数
delta *= self.m_scale
delta *= self.m_translateSpeed
# super().translate(x, y)
# super().translate(delta.x(), delta.y())
# view根据鼠标下的点作为锚点来定位scene
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
newCenter = QPoint(self.viewport().rect().width() / 2 - delta.x(),
self.viewport().rect().height() / 2 - delta.y())
self.centerOn(self.mapToScene(newCenter))
# scene在view的中心点作为锚点
self.setTransformationAnchor(QGraphicsView.AnchorViewCenter)
class NetworkScene(QGraphicsScene):
def __init__(self, ig, *__args):
super().__init__(*__args)
self.ig = ig
self.buttons = []
self.buttonLabels = []
for i in range(len(self.ig.points)):
b = PointButton(self.ig, i, self.ig.points[i].color)
# b = PointButton(str(self.ig.points[i].name))
b.setToolTip(str(self.ig.points[i].name))
b.move(self.ig.points[i].x, self.ig.points[i].y)
b.resize(POINT_SIZE, POINT_SIZE)
# palette1 = QPalette()
# # palette1.setColor(self.backgroundRole(), QColor(192,253,123)) # 设置背景颜色
# palette1.setBrush(b.backgroundRole(), QBrush(QPixmap('a.png'))) # 设置背景图片
# b.setPalette(palette1)
b.setIcon(QIcon("c_plus/%s.png"%(SHAPE_CONFIG[b.ofCommunity])))
b.setIconSize(QSize(10, 10))
textLabel = QLabel(str(i+1))
textLabel.setText(str(i+1))
textLabel.setFont(LABEL_FONT)
textLabel.move(b.mapFromGlobal(b.getGlobalPos())+QPoint(LABEL_PADDING, LABEL_PADDING))
textLabel.setWordWrap(True)
textLabel.setAttribute(Qt.WA_TranslucentBackground, True)
textLabel.raise_()
self.addWidget(textLabel)
self.addWidget(b)
b.setAttribute(Qt.WA_TranslucentBackground, True)
b.show()
self.buttonLabels.append(textLabel)
self.buttons.append(b)
self.lineItem = []
for i in range(len(self.ig.lines)):
# 初始化默认显示所有
x = self.ig.points[self.ig.lines[i].a - 1].x + POINT_SIZE / 2
y = self.ig.points[self.ig.lines[i].a - 1].y + POINT_SIZE / 2
x1 = self.ig.points[self.ig.lines[i].b - 1].x + POINT_SIZE / 2
y1 = self.ig.points[self.ig.lines[i].b - 1].y + POINT_SIZE / 2
pItem = LineItem(self.ig, i, self.ig.lines[i].color, self)
# 设置直线位于(x1, y1)和(x2, y2)之间
pItem.setLine(QLineF(x, y, x1, y1))
self.lineItem.append(pItem)
pItem.isVisible()
# 将item添加至场景中
self.addItem(pItem)
def reload(self):
for i in range(len(self.ig.points)):
self.buttons[i].move(self.ig.points[i].x, self.ig.points[i].y)
self.buttonLabels[i].move(self.ig.points[i].x+LABEL_PADDING, self.ig.points[i].y+LABEL_PADDING)
for i in range(len(self.ig.lines)):
# 初始化默认显示所有
x = self.ig.points[self.ig.lines[i].a - 1].x + POINT_SIZE / 2
y = self.ig.points[self.ig.lines[i].a - 1].y + POINT_SIZE / 2
x1 = self.ig.points[self.ig.lines[i].b - 1].x + POINT_SIZE / 2
y1 = self.ig.points[self.ig.lines[i].b - 1].y + POINT_SIZE / 2
self.lineItem[i].setLine(QLineF(x, y, x1, y1))
self.restoreScene()
def focusPoint(self, index):
for b in self.buttons:
b.setWindowOpacity(.3)
b.resize(10, 10)
self.buttons[index].setWindowOpacity(1)
self.buttons[index].resize(15, 15)
for line in self.lineItem:
if line.a == index + 1 or line.b == index + 1:
line.setOpacity(line.focus_opacity)
line.focus()
else:
line.restore(saveColor=True)
line.setOpacity(line.ignore_opacity)
def leavePoint(self, saveColor=None):
if saveColor:
for i in range(len(self.buttons)):
self.buttons[i].restore(saveColor=saveColor)
for i in range(len(self.lineItem)):
self.lineItem[i].restore(saveColor=saveColor)
else:
for i in range(len(self.buttons)):
self.buttons[i].restore()
for i in range(len(self.lineItem)):
self.lineItem[i].restore()
def restoreScene(self):
for i in range(len(self.buttons)):
self.buttons[i].show()
self.buttonLabels[i].show()
self.buttons[i].restore()
self.ig.points[i].display = True
for i in range(len(self.lineItem)):
self.lineItem[i].show()
self.lineItem[i].restore()
self.ig.lines[i].display = True
vpFrontView.update()
vpResultView.isRemoveDots = False
vpResultView.isRemovePairs = False
vpResultView.isChangeCommunity = False
vpResultView.updateEntropy()
def updateScene(self):
index = 0
shift = 10
length = len(self.ig.points)
for i in range(length):
if self.ig.points[i].display:
x = self.ig.points[i].x
y = self.ig.points[i].y
# qp.drawPoint(x, y)
# qp.drawText(x + shift, y + shift, str(self.ig.points[i].name))
index += 1
elif self.buttons[i].isVisible:
self.buttons[i].setVisible(False)
self.update()
length = len(self.ig.lines)
for i in range(length):
if not self.ig.lines[i].display and self.lineItem[i].isVisible():
self.lineItem[i].setVisible(False)
continue
elif self.ig.lines[i].display and not self.lineItem[i].isVisible():
self.lineItem[i].setVisible(True)
if self.ig.points[self.ig.lines[i].a - 1].display and self.ig.points[self.ig.lines[i].b - 1].display \
and self.ig.lines[i].display:
x = self.ig.points[self.ig.lines[i].a - 1].x + POINT_SIZE / 2
y = self.ig.points[self.ig.lines[i].a - 1].y + POINT_SIZE / 2
x1 = self.ig.points[self.ig.lines[i].b - 1].x + POINT_SIZE / 2
y1 = self.ig.points[self.ig.lines[i].b - 1].y + POINT_SIZE / 2
# qp.drawLine(x, y, x1, y1)
else:
self.ig.lines[i].display = False
self.lineItem[i].setVisible(False)
def mouseDoubleClickEvent(self, QGraphicsSceneMouseEvent):
self.restoreScene()
class ViewPainter(QWidget):
def __init__(self, ig):
super().__init__()
self.ig = ig
self.initUI()
def initUI(self):
self.setWindowTitle('绘制点')
self.resize(500, 500)
# self.show()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawPoints(qp)
qp.end()
def drawPoints(self, qp):
qp.setPen(QtCore.Qt.red)
size = self.size()
length = len(self.ig.points)
pos = []
index = 0
shift = 10
for i in range(length):
if self.ig.points[i].display:
x = self.ig.points[i].x
y = self.ig.points[i].y
# qp.drawPoint(x, y)
pen = qp.pen()
pen.setColor(QColor(self.ig.points[i].color))