-
Notifications
You must be signed in to change notification settings - Fork 33
/
path_igraph.py
210 lines (169 loc) · 5.9 KB
/
path_igraph.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""igraph based pathfinders."""
import functools
from collections import defaultdict
from ..core import (
ContractionTree,
PartitionTreeBuilder,
jitter_dict,
)
from ..hypergraph import (
calc_edge_weight_float,
calc_node_weight_float,
)
from ..hyperoptimizers.hyper import register_hyper_function
from ..utils import get_rng
def oe_to_igraph(
inputs, output, size_dict, weight_nodes="const", weight_edges="log"
):
"""Convert opt_einsum format to igraph graph incl. weights."""
import igraph as ig
G = ig.Graph()
# which positions each edge links
ind2terms = defaultdict(list)
for i, term in enumerate(inputs):
nweight = calc_node_weight_float(term, size_dict, weight_nodes)
G.add_vertex(str(i), weight=nweight)
for ix in term:
if ix not in output:
ind2terms[ix].append(str(i))
for ix, enodes in ind2terms.items():
if len(enodes) != 2:
continue
eweight = calc_edge_weight_float(ix, size_dict, weight_edges)
G.add_edge(*enodes, ind=ix, weight=eweight)
return G
def igraph_subgraph_find_membership(
inputs,
output,
size_dict,
weight_nodes="const",
weight_edges="log",
method="spinglass",
parts=2,
seed=None,
**igraph_opts,
):
G = oe_to_igraph(inputs, output, size_dict, weight_nodes, weight_edges)
# first check for disconnected components
components = G.components()
if len(components) > 1:
return components.membership
weight_lbl = "weight" if weight_edges != "const" else None
nd_weight_lbl = "weight" if weight_nodes != "const" else None
if method == "spinglass":
igraph_opts.setdefault("spins", parts)
clustering = G.community_spinglass(weight_lbl, **igraph_opts)
elif method == "infomap":
clustering = G.community_infomap(
weight_lbl, nd_weight_lbl, **igraph_opts
)
elif method == "label_propagation":
rng = get_rng(seed)
initial = [rng.choice(range(parts)) for _ in range(len(G.vs))]
clustering = G.community_label_propagation(
weight_lbl, initial=initial, **igraph_opts
)
elif method == "multilevel":
clustering = G.community_multilevel(weight_lbl, **igraph_opts)
elif method == "leading_eigenvector":
igraph_opts.setdefault("clusters", parts)
clustering = G.community_leading_eigenvector(
weights=weight_lbl, **igraph_opts
)
return clustering.membership
igraph_to_tree = PartitionTreeBuilder(igraph_subgraph_find_membership)
trial_igraph_partition = igraph_to_tree.trial_fn
def trial_igraph_dendrogram(
inputs,
output,
size_dict,
weight_nodes="const",
weight_edges="log",
random_strength=0.1,
method="betweenness",
**kwargs,
):
"""A single, repeatable, igraph trial run. This is for igraph methods that
naturally produce a dendrogram (== ssa_path).
"""
G = oe_to_igraph(
inputs,
output,
size_dict=jitter_dict(size_dict, random_strength),
weight_nodes=weight_nodes,
weight_edges=weight_edges,
)
if weight_edges != "const":
kwargs.setdefault("weights", "weight")
if method == "betweenness":
kwargs.setdefault("clusters", 2)
kwargs.setdefault("directed", False)
dendrogram = G.community_edge_betweenness(**kwargs)
elif method == "walktrap":
kwargs.setdefault("steps", 100)
dendrogram = G.community_walktrap(**kwargs)
elif method == "fastgreedy":
dendrogram = G.community_fastgreedy(**kwargs)
else:
raise ValueError("Invalid method: '{}'.".format(method))
ssa_path = dendrogram.merges
return ContractionTree.from_path(
inputs, output, size_dict, ssa_path=ssa_path, autocomplete=True
)
# ----------------------------- HYPER REGISTERS ----------------------------- #
register_hyper_function(
name="walktrap",
ssa_func=functools.partial(trial_igraph_dendrogram, method="walktrap"),
space={
"random_strength": {"type": "FLOAT_EXP", "min": 0.01, "max": 10.0},
"steps": {"type": "INT", "min": 4, "max": 200},
},
)
register_hyper_function(
name="betweenness",
ssa_func=functools.partial(trial_igraph_dendrogram, method="betweenness"),
space={
"random_strength": {"type": "FLOAT_EXP", "min": 0.01, "max": 10.0},
},
)
def trial_spinglass(
inputs, output, size_dict, icool_fact=0.01, igamma=0.01, **kwargs
):
return trial_igraph_partition(
inputs,
output,
size_dict,
method="spinglass",
gamma=(1 - igamma),
cool_fact=(1 - icool_fact),
**kwargs,
)
register_hyper_function(
name="spinglass",
ssa_func=trial_spinglass,
space={
"random_strength": {"type": "FLOAT_EXP", "min": 0.001, "max": 1.0},
"weight_edges": {"type": "STRING", "options": ["const", "log"]},
"start_temp": {"type": "FLOAT_EXP", "min": 0.5, "max": 5.0},
"stop_temp": {"type": "FLOAT_EXP", "min": 0.001, "max": 0.2},
"icool_fact": {"type": "FLOAT_EXP", "min": 0.001, "max": 0.05},
"update_rule": {"type": "STRING", "options": ["config", "simple"]},
"igamma": {"type": "FLOAT_EXP", "min": 0.001, "max": 0.1},
"cutoff": {"type": "INT", "min": 10, "max": 40},
"parts": {"type": "INT", "min": 2, "max": 16},
"parts_decay": {"type": "FLOAT", "min": 0.0, "max": 1.0},
},
)
register_hyper_function(
name="labelprop",
ssa_func=functools.partial(
trial_igraph_partition, method="label_propagation"
),
space={
"random_strength": {"type": "FLOAT_EXP", "min": 0.01, "max": 10.0},
"weight_edges": {"type": "STRING", "options": ["const", "log"]},
"cutoff": {"type": "INT", "min": 10, "max": 40},
"parts": {"type": "INT", "min": 2, "max": 16},
"parts_decay": {"type": "FLOAT", "min": 0.0, "max": 1.0},
},
)