-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopologies.py
66 lines (56 loc) · 1.9 KB
/
topologies.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
import networkx as nx
import random
import math
__all__ = [
"Topology",
"ChainTopology",
"BinaryTreeTopology",
"DoubleBinaryTreeTopology",
]
class Topology():
def __init__(self, num_workers):
self.num_workers = num_workers
def neighbors(self, worker):
return []
class ChainTopology(Topology):
def __init__(self, num_workers):
super().__init__(num_workers=num_workers)
def neighbors(self, worker):
if self.num_workers == 1:
return []
elif worker == 0:
return [1]
elif worker == self.num_workers - 1:
return [worker - 1]
else:
return [worker - 1, worker + 1]
class BinaryTreeTopology(Topology):
def __init__(self, num_workers):
super().__init__(num_workers=num_workers)
def neighbors(self, worker):
if self.num_workers == 1:
return []
elif worker == 0:
return [1]
else:
parent = worker // 2
children = [worker * 2, worker * 2 + 1]
children = [c for c in children if c < self.num_workers]
return [parent, *children]
class DoubleBinaryTreeTopology(BinaryTreeTopology):
def __init__(self, num_workers):
super().__init__(num_workers=num_workers)
def neighbors(self, worker):
neighbors = super().neighbors(worker)
reverse_neighbors = self.reverse_neighbors(worker)
return neighbors, reverse_neighbors
def reverse_neighbors(self, worker):
if worker == self.num_workers - 1:
return [worker - 1]
else:
worker = self.num_workers - 1 - worker
parent = worker // 2
children = [worker * 2, worker * 2 + 1]
children = [self.num_workers - 1 - c for c in children if c < self.num_workers]
parent = self.num_workers - 1 - parent
return [parent, *children]