@@ -63,25 +63,32 @@ def uniform_spanning_tree(graph, choice=random.choice):
63
63
64
64
65
65
class PopulatedGraph :
66
+ __slots__ = [
67
+ "graph" ,
68
+ "subsets" ,
69
+ "population" ,
70
+ "tot_pop" ,
71
+ "ideal_pop" ,
72
+ "epsilon" ,
73
+ "degrees"
74
+ ]
75
+
66
76
def __init__ (self , graph , populations , ideal_pop , epsilon ):
67
77
self .graph = graph
68
78
self .subsets = {node : {node } for node in graph .node_indicies }
69
79
self .population = populations .copy ()
70
80
self .tot_pop = sum (self .population .values ())
71
81
self .ideal_pop = ideal_pop
72
82
self .epsilon = epsilon
73
- self ._degrees = {node : graph .degree (node ) for node in graph . node_indicies }
83
+ self .degrees = {node : graph .degree (node ) for node in graph }
74
84
75
85
def __iter__ (self ):
76
86
return iter (self .graph )
77
87
78
- def degree (self , node ):
79
- return self ._degrees [node ]
80
-
81
88
def contract_node (self , node , parent ):
82
89
self .population [parent ] += self .population [node ]
83
90
self .subsets [parent ] |= self .subsets [node ]
84
- self ._degrees [parent ] -= 1
91
+ self .degrees [parent ] -= 1
85
92
86
93
def has_ideal_population (self , node ):
87
94
return (
@@ -94,26 +101,26 @@ def has_ideal_population(self, node):
94
101
95
102
def find_balanced_edge_cuts_contraction (h , choice = random .choice ):
96
103
# this used to be greater than 2 but failed on small grids:(
97
- root = choice ([x for x in h if h .degree ( x ) > 1 ])
104
+ root = choice ([x for x in h if h .degrees [ x ] > 1 ])
98
105
# BFS predecessors for iteratively contracting leaves
99
106
pred = predecessors (h .graph , root )
100
107
101
108
cuts = []
102
- leaves = deque (x for x in h if h .degree ( x ) == 1 )
109
+ leaves = deque (x for x in h if h .degrees [ x ] == 1 )
103
110
while len (leaves ) > 0 :
104
111
leaf = leaves .popleft ()
105
112
if h .has_ideal_population (leaf ):
106
113
cuts .append (Cut (edge = (leaf , pred [leaf ]), subset = h .subsets [leaf ].copy ()))
107
114
# Contract the leaf:
108
115
parent = pred [leaf ]
109
116
h .contract_node (leaf , parent )
110
- if h .degree ( parent ) == 1 and parent != root :
117
+ if h .degrees [ parent ] == 1 and parent != root :
111
118
leaves .append (parent )
112
119
return cuts
113
120
114
121
115
122
def find_balanced_edge_cuts_memoization (h , choice = random .choice ):
116
- root = choice ([x for x in h if h .degree ( x ) > 1 ])
123
+ root = choice ([x for x in h if h .degrees [ x ] > 1 ])
117
124
pred = predecessors (h .graph , root )
118
125
succ = successors (h .graph , root )
119
126
total_pop = h .tot_pop
0 commit comments