-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasenetwork.py
90 lines (74 loc) · 2.15 KB
/
basenetwork.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import copy
from PyQt5.QtCore import (
QRect,
)
import utils
class BaseNetwork(object):
def __init__(self):
self.nodes = set()
def get_active_nodes(self):
return [node for node in self.nodes if node.is_active()]
def is_stabilised(self):
return not self.get_active_nodes()
def __iadd__(self, node):
self.nodes.add(node)
node.net = self
return self
def connect(self, node1, node2):
for node in node1, node2:
self.nodes.add(node)
node1.connect(node2)
def move(self):
node = utils.random_pick( self.get_active_nodes() )
info = {'prestate': copy.copy(node)}
rule = node.move()
info['rule'] = rule
info['poststate'] = copy.copy(node)
return info
def run(self):
while not self.is_stabilised():
yield self.move()
def draw_edge(self, painter, edge):
node1, node2 = edge
painter.drawLine(node1.centre(), node2.centre())
def draw(self, painter):
# Edges drawing
edges = {
frozenset((node, neighbour))
for node in self.nodes
for neighbour in node.neighbours
}
for edge in edges:
self.draw_edge(painter, edge)
# Nodes drawing
for node in self.nodes:
node.draw(painter)
def boundingBox(self):
margin = 25
mini_x = min(node._x for node in self.nodes)
maxi_x = max(node._x for node in self.nodes)
mini_y = min(node._y for node in self.nodes)
maxi_y = max(node._y for node in self.nodes)
width = maxi_x - mini_x
height = maxi_y - mini_y
return QRect(
mini_x-margin,
mini_y-margin,
2*margin+width,
2*margin+height
)
def adjustedBoundingBox(self, painter):
boundingBox = self.boundingBox()
bbRatio = boundingBox.height() / boundingBox.width()
viewPort = painter.viewport()
vpRatio = viewPort.height() / viewPort.width()
if vpRatio > bbRatio:
diff = boundingBox.width() * (vpRatio-bbRatio)
boundingBox.adjust( 0, -diff/2, 0, diff/2)
elif vpRatio < bbRatio:
diff = boundingBox.height() * (1/vpRatio-1/bbRatio)
boundingBox.adjust( -diff/2, 0, diff/2, 0 )
return boundingBox