-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcursor.py
More file actions
74 lines (58 loc) · 1.79 KB
/
cursor.py
File metadata and controls
74 lines (58 loc) · 1.79 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
#!/usr/bin/python3
#
# By Sebastian Raaphorst, 2018
#
# A visual example of the dispersive fly optimization problem where the flies attempt to chase around
# the moving cursor.
import sys
from time import sleep
from math import sqrt
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtCore import Qt
import numpy as np
from dispersive_flies import DispersiveFlies, euclidean_metric
position = [0, 0]
def update(ex):
def update_fn(flies):
ex.flies = flies
ex.update()
return update_fn
class Cursor(QWidget):
def __init__(self, width=800, height=800):
self.flies = []
super().__init__()
self.setGeometry(100, 100, width, height)
self.setWindowTitle('Dispersive Flies Optimization')
self.show()
self.setMouseTracking(True)
self.df = DispersiveFlies(2, fitness, flies=50, dim_max=(800 * np.ones(2)),
metric=euclidean_metric, end_round=update(self))
def paintEvent(self, _):
self.repaint()
def repaint(self):
qp = QPainter()
qp.begin(self)
size = self.size()
qp.setPen(Qt.black)
qp.setBrush(Qt.black)
qp.drawRect(0, 0, size.width(), size.height())
# Draw the flies.
qp.setPen(Qt.white)
qp.setBrush(Qt.white)
for (x, y) in self.flies:
qp.drawEllipse(x-2, y-2, 4, 4)
qp.end()
def mouseMoveEvent(self, event):
self.df.run_round()
position[0:2] = (event.x(), event.y())
self.update()
sleep(0.1)
def fitness(fly):
px, py = position
fx, fy = fly
return -sqrt((px - fx)**2 + (py - fy)**2)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Cursor()
sys.exit(app.exec_())