Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- '''
- Parameters
- - number of nodes in network
- - number of nodes each node is subscribed to
- Variants
- - change network topology (power law, preferential attachment)
- - change rules that individual nodes use to update state
- -- each node might only update each cycle with probability 20%
- - change information in state, such as adding surveys
- '''
- class Node:
- def __init__(self, node_id):
- self.node_id = node_id
- self.state = random.randint(1,2)
- self.subscribed = []
- pass
- def ConnectToRandomNodes(self, node_max, connection_count):
- for idx in range(connection_count):
- i = -1
- while 1:
- i = random.randint(0,node_max-1)
- if i not in self.subscribed and i != self.node_id:
- #do not allow self connections and double connections
- break
- self.subscribed.append(i) #add i to list of nodes subscribed
- def Update(self, nodes): # one round of consensus
- s1 = 0 #count of nodes in state 1, who are subscribed to
- s2 = 0 #count of nodes in state 2, who are subscribed to
- for i in self.subscribed:
- if nodes[i].state == 1:
- s1 += 1
- if nodes[i].state == 2:
- s2 += 1
- #choose update rule
- #look at subscribed peers, choose state based upon peer state
- if random.randint(1,s1+s2) <= s1:
- self.state = 1
- else:
- self.state = 2
- #if more than 80% of peers are in agreement, snap to agreement
- if float(s1) / float(s1+s2) > 0.8:
- self.state = 1
- if float(s2) / float(s1+s2) > 0.8:
- self.state = 2
- class Graph:
- def init(self, node_count):
- self.nodes = {}
- self.round_count = 0
- self.converged = False
- #generate n nodes, connect them to each other
- for i in range(node_count):
- node_id = len(self.nodes)
- x = Node(node_id)
- #connect each node to 8 other nodes
- x.ConnectToRandomNodes(node_count, 12) #set node connections
- self.nodes[node_id] = x
- def round(self): #one round of consensus
- index = range(len(self.nodes))
- random.shuffle(index) #update nodes in random order
- for i in index:
- self.nodes[i].Update(self.nodes) #apply one round of consensus
- self.round_count += 1
- def printReport(self):
- s1 = 0
- s2 = 0
- for i in range(len(self.nodes)):
- if self.nodes[i].state == 1:
- s1 += 1
- if self.nodes[i].state == 2:
- s2 += 1
- print("Round %d: node_count= %d, state1= %d, state2= %d" % (self.round_count, len(self.nodes), s1,s2))
- if (s1 == 0) or (s2 == 0):
- self.converged = True
- node_count = 1280
- g = Graph()
- g.init(node_count)
- g.printReport()
- while g.converged == False:
- g.round()
- g.printReport()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement