-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBayanImplied.py
1514 lines (1315 loc) · 62.1 KB
/
BayanImplied.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests, zipfile, shutil, json
import pandas as pd
import networkx as nx
from io import BytesIO
import numpy as np
import time
import multiprocessing
import pycombo
from itertools import combinations
from gurobipy import *
from networkx.algorithms.connectivity import minimum_st_node_cut
from joblib import Parallel, delayed, parallel_backend
from itertools import chain
# from pyomo.environ import *
# from pyomo.opt import SolverFactory
def get_graph_from_network_name(network_name, sub_name=None):
"""
Method to create a networkx Graph from network names listed at https://networks.skewed.de/
"""
# Defining the network information url
info_url = "https://networks.skewed.de/api/net/%s" % network_name
req = requests.get(info_url)
info_dict = json.loads(req.text)
if sub_name is None:
net = info_dict['nets'][0]
else:
net = sub_name
# Check and store the names of the available node/edge properties and whether the graph is directed
if net == network_name:
vertex_properties = []
for prop in info_dict['analyses']["vertex_properties"]:
vertex_properties.append(prop[0])
edge_properties = []
for prop in info_dict['analyses']["edge_properties"]:
edge_properties.append(prop[0])
is_directed = info_dict['analyses']['is_directed']
else:
vertex_properties = []
for prop in info_dict['analyses'][net]["vertex_properties"]:
vertex_properties.append(prop[0])
edge_properties = []
for prop in info_dict['analyses'][net]["edge_properties"]:
edge_properties.append(prop[0])
is_directed = info_dict['analyses'][net]['is_directed']
# Defining the zip file URL
url = "https://networks.skewed.de/net/%s/files/%s.csv.zip" % (network_name, net)
# Downloading the file by sending the request to the URL
req = requests.get(url)
# extracting the zip file contents
z = zipfile.ZipFile(BytesIO(req.content))
if os.path.isdir(network_name + "_files"):
shutil.rmtree(network_name + "_files")
# creating a dir to extract the files into
os.mkdir(network_name + "_files")
z.extractall(os.getcwd() + '/%s_files' % network_name)
# read in the dataframes of the nodes and edges of the network
nodes_df = pd.read_csv(network_name + "_files/nodes.csv")
edges_df = pd.read_csv(network_name + "_files/edges.csv")
# Create the graph
G = nx.Graph()
# Add the nodes and their attributes to the graph
node_attrs = {}
for row in range(nodes_df.shape[0]):
G.add_node(nodes_df.iloc[row][0])
vertex_dict = {}
for i in range(len(vertex_properties)):
if vertex_properties[i] == '_pos':
vertex_dict[vertex_properties[i]] = [float(y) for y in nodes_df.iloc[row][i + 1][7:-2].split(",")]
else:
vertex_dict[vertex_properties[i]] = nodes_df.iloc[row][i + 1]
node_attrs[nodes_df.iloc[row][0]] = vertex_dict
nx.set_node_attributes(G, node_attrs)
# Add the edges and their attributes to the graph
edge_attrs = {}
is_multigraph = False
for row in range(edges_df.shape[0]):
is_multigraph = is_multigraph or G.has_edge(edges_df.iloc[row][0], edges_df.iloc[row][1])
G.add_edge(edges_df.iloc[row][0], edges_df.iloc[row][1])
edge_dict = {}
for i in range(len(edge_properties)):
edge_dict[edge_properties[i]] = edges_df.iloc[row][i + 2]
edge_attrs[(edges_df.iloc[row][0], edges_df.iloc[row][1])] = edge_dict
nx.set_edge_attributes(G, edge_attrs)
# #actual_weight is the attribute that stores the edge weight
# for edge in G.edges():
# G.edges[edge]['constrained_modularity'] = False
# if 'weight' in G.edges[edge]:
# G.edges[edge]['actual_weight'] = G.edges[edge]['weight']
# else:
# G.edges[edge]['actual_weight'] = 1
# #weight is the attribute that stores the modularity for pair i, j. This is because pycombo needs the modularity to be the 'weight' attribute
# ModularityMatrix = nx.modularity_matrix(G, weight="actual_weight")
# for edge in G.edges():
# G.edges[edge]['weight'] = ModularityMatrix[int(edge[0]), int(edge[1])]
# #super node of stores all the nodes that are a part of this super node
# for node in G.nodes():
# G.nodes[node]['super node of'] = [node]
# If G is a multigraph then the edge attributes correspond to the attributes of the last seen edge as in the data
if is_multigraph:
print("%s is a multigraph but has been loaded as a simple graph" % network_name)
shutil.rmtree(network_name + "_files")
return G
def get_local_clustering_coefficient(G, node: int):
"""
Returns the clustering coefficient for the input node in the input graph
"""
neighbours = nx.adjacency_matrix(G)[:node].indices
if neighbours.shape[0] <= 1:
return 0.0
num_possible_edges = ((neighbours.shape[0]) * (neighbours.shape[0] - 1)) / 2
num_actual_edges = 0
for neighbour in neighbours:
num_actual_edges += np.intersect1d(neighbours, nx.adjacency_matrix(G)[:neighbour].indices).shape[0]
num_actual_edges = num_actual_edges / 2
return num_actual_edges / num_possible_edges
def clique_filtering(G, resolution):
"""
Returns G' which is a clique reduction on the input graph G
"""
lcc_dict = {}
for node in G.nodes():
lcc_dict[node] = get_local_clustering_coefficient(G, node)
shrink_dict = {}
for node in G.nodes():
skip = False
for n in G.nodes():
if n in shrink_dict and shrink_dict[n] == node and n != node:
skip = True
if skip:
shrink_dict[node] = node
continue
# neighbours = nx.adjacency_matrix(G)[:node].indices
neighbours = nx.adjacency_matrix(G)[[node][:]].indices
if neighbours.shape[0] == 1:
shrink_dict[node] = neighbours[0]
continue
count_of_ones = 0
count_of_not_one = 0
not_one_neighbour = -1
for neighbour in neighbours:
if lcc_dict[neighbour] == 1:
count_of_ones += 1
else:
count_of_not_one += 1
not_one_neighbour = neighbour
if count_of_ones == neighbours.shape[0] - 1 and count_of_not_one == 1:
shrink_dict[node] = not_one_neighbour
if node not in shrink_dict.keys():
shrink_dict[node] = node
G_prime = G.copy()
# for key in shrink_dict:
# G_prime.nodes[key]['super node of'] = [key]
# print(shrink_dict)
for key in shrink_dict:
if key != shrink_dict[key]:
G_prime.nodes[shrink_dict[shrink_dict[key]]]['super node of'].extend(G_prime.nodes[key]['super node of'])
# G_prime.nodes[shrink_dict[key]]['super node of'].extend(G_prime.nodes[key]['super node of'])
edges_to_del = G_prime.edges(key)
total_weight = 0
for edge in edges_to_del:
if 'actual_weight' in G_prime.edges[edge]:
total_weight += 2 * G_prime.edges[edge]['actual_weight']
else:
total_weight += 2
if G_prime.has_edge(shrink_dict[shrink_dict[key]], shrink_dict[shrink_dict[key]]):
G_prime.edges[(shrink_dict[shrink_dict[key]], shrink_dict[shrink_dict[key]])][
'actual_weight'] += total_weight
G_prime.edges[(shrink_dict[shrink_dict[key]], shrink_dict[shrink_dict[key]])][
'constrained_modularity'] = False
# pass
else:
G_prime.add_edge(shrink_dict[shrink_dict[key]], shrink_dict[shrink_dict[key]],
actual_weight=total_weight, weight=0, constrained_modularity=False)
G_prime.remove_node(key)
G_prime = nx.convert_node_labels_to_integers(G_prime)
# ModularityMatrix = nx.modularity_matrix(G_prime, weight="actual_weight")
ModularityMatrix = get_modularity_matrix(G_prime, resolution)
for edge in G_prime.edges():
G_prime.edges[edge[0], edge[1]]["weight"] = ModularityMatrix[edge[0], edge[1]]
return G_prime
def find_in_list_of_list(mylist, char):
for sub_list in mylist:
if char in sub_list:
return (mylist.index(sub_list))
raise ValueError("'{char}' is not in list".format(char=char))
def model_to_communities(var_vals, Graph):
"""
Method that outputs communities with input model variable values and the Graph
"""
clustered = []
for v in var_vals:
if var_vals[v] != 1:
clustered.append((v).split(","))
i = 0
visited_endpoints = []
group = []
for pair in clustered:
if pair[0] not in visited_endpoints and pair[1] not in visited_endpoints and pair[0] != pair[1]:
visited_endpoints.append(pair[0])
visited_endpoints.append(pair[1])
group.append([])
(group[i]).append(pair[0])
(group[i]).append(pair[1])
i = i + 1
if pair[0] not in visited_endpoints and pair[1] in visited_endpoints:
index_one = find_in_list_of_list(group, pair[1])
(group[index_one]).append(pair[0])
visited_endpoints.append(pair[0])
if pair[1] not in visited_endpoints and pair[0] in visited_endpoints:
index_zero = find_in_list_of_list(group, pair[0])
(group[index_zero]).append(pair[1])
visited_endpoints.append(pair[1])
if pair[0] in visited_endpoints and pair[1] in visited_endpoints:
index_zero = find_in_list_of_list(group, pair[0])
index_one = find_in_list_of_list(group, pair[1])
if index_zero != index_one:
group[index_zero] = group[index_zero] + group[index_one]
del group[index_one]
i = i - 1
for node in (Graph).nodes():
if str(node) not in visited_endpoints:
group.append([str(node)])
for i in range(len(group)):
for j in range(len(group[i])):
group[i][j] = int(group[i][j])
for c in range(len(group)):
group[c].sort()
group.sort()
return group
def decluster_communities(group, Graph, isolated_nodes):
"""
Method to get communities based on the original graph. Note, input Graph is the reduced graph.
"""
group_declustered = []
for comm in group:
new_comm = []
for node in comm:
if 'super node of' in Graph.nodes[int(node)]:
node_list = Graph.nodes[int(node)]['super node of']
new_comm = new_comm + node_list
else:
new_comm.append(int(node))
group_declustered.append(new_comm)
for n in isolated_nodes:
group_declustered.append([n])
for c in range(len(group_declustered)):
group_declustered[c].sort()
group_declustered.sort()
return group_declustered
def separating_set_parallel(i, j, Graph):
triads = []
minimum_vertex_cut = minimum_st_node_cut(Graph, i, j)
for k in minimum_vertex_cut:
triads.append(list(np.sort([i, j, k])))
return triads
def lp_formulation_pyomo(Graph, AdjacencyMatrix, ModularityMatrix, size, order, isolated_nodes, lp_method,
warmstart=int(0),
branching_priotiy=int(0)):
"""
Method to create the LP model and run it for the root node
"""
formulation_time_start = time.time()
list_of_cut_triads = []
pairs = set(combinations(np.sort(list((Graph).nodes())), 2))
self_edges = set([(i, i) for i in (Graph).nodes()])
pairs_with_edges = set((Graph).edges()) - self_edges
pairs_without_edges = pairs - pairs_with_edges
pairs_without_edges = list(pairs_without_edges)
pairs_with_edges = list(pairs_with_edges)
# JOBLIB
with parallel_backend(backend='loky', n_jobs=-1):
res = Parallel()(delayed(separating_set_parallel)(pair[0], pair[1], Graph) for pair in pairs_without_edges)
list_of_cut_triads = list(chain(*res))
for pair in pairs_with_edges:
i = pair[0]
j = pair[1]
removed_edge = False
if Graph.has_edge(i, j):
removed_edge = True
attr_dict = Graph.edges[i, j]
Graph.remove_edge(i, j)
minimum_vertex_cut = minimum_st_node_cut(Graph, i, j)
for k in minimum_vertex_cut:
list_of_cut_triads.append(list(np.sort([i, j, k])))
if removed_edge:
Graph.add_edge(i, j, weight=attr_dict["weight"], constrained_modularity=attr_dict["constrained_modularity"],
actual_weight=attr_dict["actual_weight"])
# Create model
model = ConcreteModel()
# Define index sets
model.node_pairs = Set(
initialize=[(i, j) for i in range(len(Graph.nodes())) for j in range(i + 1, len(Graph.nodes()))], ordered=True)
# Define variables
model.x = Var(model.node_pairs, within=Binary)
# Define objective
def obj_expression(m):
return sum(ModularityMatrix[i, j] * (1 - m.x[i, j]) for (i, j) in m.node_pairs)
model.obj = Objective(rule=obj_expression, sense=maximize)
# Define constraints
def triangle_constraints(m, i, j, k):
return m.x[i, k] <= m.x[i, j] + m.x[j, k]
model.triangle1 = Constraint(list_of_cut_triads, rule=triangle_constraints)
def triangle_constraints2(m, i, j, k):
return m.x[i, j] <= m.x[i, k] + m.x[j, k]
model.triangle2 = Constraint(list_of_cut_triads, rule=triangle_constraints2)
def triangle_constraints3(m, i, j, k):
return m.x[j, k] <= m.x[i, j] + m.x[i, k]
model.triangle3 = Constraint(list_of_cut_triads, rule=triangle_constraints3)
formulation_time = time.time() - formulation_time_start
# Create a solver
solver = SolverFactory("appsi_highs") # SolverFactory('gurobi')
solver.options['Method'] = lp_method
solver.options['Crossover'] = 0
# Set solver options
solver.options['Threads'] = min(64, multiprocessing.cpu_count())
solver.options['OutputFlag'] = 0
# Using a warm start
if warmstart == 1:
# Solution from Combo algorithm to be used as warm-start
partition = pycombo.execute(Graph, modularity_resolution=resolution)
community_combo = convert_to_com_list(partition[0])
for i in (Graph).nodes():
for j in filter(lambda x: x > i, (Graph).nodes()):
if find_in_list_of_list(community_combo, i) == find_in_list_of_list(community_combo, j):
model.x[i, j].value = 0
else:
model.x[i, j].value = 1
solver.options['WarmStart'] = 1
# Solve the model
start_time = time.time()
results = solver.solve(model, tee=False)
solveTime = (time.time() - start_time)
if results.solver.status == SolverStatus.ok and results.solver.termination_condition == TerminationCondition.optimal:
# Objective value
objectivevalue = np.round(((2 * model.obj() + (ModularityMatrix.trace())) / np.sum(AdjacencyMatrix)), 8)
# Variable values
var_vals = {str(i) + ',' + str(j): model.x[i, j].value for (i, j) in model.node_pairs}
return objectivevalue, var_vals, model, list_of_cut_triads, formulation_time, solveTime
else:
print("Solver status:", results.solver.status)
print("Termination condition:", results.solver.termination_condition)
raise ValueError("The solver did not find an optimal solution.")
def run_lp_pyomo(model, Graph, fixed_ones, fixed_zeros, resolution, lp_method):
"""
Run the LP based on model and the original Graph as input
"""
ModularityMatrix = get_modularity_matrix(Graph, resolution)
AdjacencyMatrix = nx.adjacency_matrix(Graph, weight='actual_weight')
# Fix variables
for (i, j) in fixed_ones:
model.x[i, j].fix(1)
for (i, j) in fixed_zeros:
model.x[i, j].fix(0)
# Create a solver
solver = SolverFactory('gurobi')
solver.options['Method'] = lp_method
solver.options['Crossover'] = 0
solver.options['Threads'] = min(64, multiprocessing.cpu_count())
solver.options['OutputFlag'] = 0
# Solve the model
start_time = time.time()
results = solver.solve(model, tee=False)
solveTime = (time.time() - start_time)
if results.solver.status == SolverStatus.ok and results.solver.termination_condition == TerminationCondition.optimal:
# Objective value
objectivevalue = np.round(((2 * model.obj() + (ModularityMatrix.trace())) / np.sum(AdjacencyMatrix)), 8)
# Variable values
var_vals = {(i, j): model.x[i, j].value for (i, j) in model.node_pairs}
return objectivevalue, var_vals, model
else:
print("Solver status:", results.solver.status)
print("Termination condition:", results.solver.termination_condition)
return -1, -1, model
def VariableValue(var_vals, i,j):
value = 0
if i < j:
value = var_vals[str(i)+","+str(j)]
elif i >j:
value = var_vals[str(j)+","+str(i)]
return round(value, 5)
def TwoPartitionSeperation(var_vals):
var_vals_detail = {}
for key in var_vals:
i,j = [int(a) for a in key.split(",")]
if i not in var_vals_detail:
var_vals_detail[i] = {'0':[], '1':[], '0-1':[]}
if j not in var_vals_detail:
var_vals_detail[j] = {'0':[], '1':[], '0-1':[]}
if round(var_vals[key],3) == 0:
var_vals_detail[i]['0'].append(j)
var_vals_detail[j]['0'].append(i)
elif round(var_vals[key],3) == 1:
var_vals_detail[i]['1'].append(j)
var_vals_detail[j]['1'].append(i)
else:
var_vals_detail[i]['0-1'].append(j)
var_vals_detail[j]['0-1'].append(i)
Cuts = []
skipW = 0
for v in var_vals_detail:
# S =[]
# S.append(v)
T =[]
for w in var_vals_detail[v]['0-1']:
if len(T)==0:
T.append(w)
continue
for w_old in T:
if VariableValue(var_vals, w,w_old) != 0:
skipW = 1
break
if skipW:
skipW = 0
continue
T.append(w)
# Check if X[{v}:T] >1
if sum([VariableValue(var_vals, v,w) for w in T]) > 1 :
# add X[{v}:T] <= 1 cut
Cuts.append([str(v)+","+str(w) for w in T if v <w] + [str(w)+","+str(v) for w in T if w <v] )
if Cuts:
return Cuts
# Run the second heuristic if we could not find any cut with the first one
for v in var_vals_detail:
T =[]
for w in var_vals_detail[v]['0-1']:
if len(T)==0:
T.append(w)
continue
sumXij = sum ([ VariableValue(var_vals, w,w_old) for w_old in T])
if VariableValue(var_vals, w,v) - sumXij > 0:
T.append(w)
# Check if X[{v}:T] >1
if sum([VariableValue(var_vals, v,w) for w in T]) >1 :
# add X[{v}:T] <= 1 cut
Cuts.append([str(v)+","+str(w) for w in T if v <w] + [str(w)+","+str(v) for w in T if w <v] )
return Cuts
def AddCuts(model, Cuts):
if Cuts:
for cut in Cuts:
model.addConstr(quicksum([model.getVarByName(var_name) for var_name in cut]) <=1, name='cut_')
return model
def lp_formulation(Graph, AdjacencyMatrix, ModularityMatrix, isolated_nodes,
lp_method, warmstart=int(0), branching_priotiy=int(0)):
"""
Method to create the LP model and run it for the root node
"""
validinequality = 0 # Parameter to add valid inequality cust to root node or not
formulation_time_start = time.time()
list_of_cut_triads = []
pairs = set(combinations(np.sort(list((Graph).nodes())), 2))
self_edges = set([(i, i) for i in (Graph).nodes()])
pairs_with_edges = set((Graph).edges()) - self_edges
pairs_without_edges = pairs - pairs_with_edges
pairs_without_edges = list(pairs_without_edges)
pairs_with_edges = list(pairs_with_edges)
# JOBLIB
with parallel_backend(backend='loky', n_jobs=-1):
res = Parallel()(delayed(separating_set_parallel)(pair[0], pair[1], Graph) for pair in pairs_without_edges)
list_of_cut_triads = list(chain(*res))
for pair in pairs_with_edges:
i = pair[0]
j = pair[1]
removed_edge = False
if Graph.has_edge(i, j):
removed_edge = True
attr_dict = Graph.edges[i, j]
Graph.remove_edge(i, j)
minimum_vertex_cut = minimum_st_node_cut(Graph, i, j)
for k in minimum_vertex_cut:
list_of_cut_triads.append(list(np.sort([i, j, k])))
if removed_edge:
Graph.add_edge(i, j, weight=attr_dict["weight"], constrained_modularity=attr_dict["constrained_modularity"],
actual_weight=attr_dict["actual_weight"])
x = {}
model = Model("Modularity maximization")
model.setParam(GRB.param.OutputFlag, 0)
model.setParam(GRB.param.Method, lp_method)
model.setParam(GRB.Param.Crossover, 0)
model.setParam(GRB.Param.Threads, min(64, multiprocessing.cpu_count()))
for i in range(len(Graph.nodes())):
for j in range(i + 1, len(Graph.nodes())):
x[(i, j)] = model.addVar(lb=0, ub=1, vtype=GRB.CONTINUOUS, name=str(i) + ',' + str(j))
model.update()
OFV = 0
for i in range(len(Graph.nodes())):
for j in range(i + 1, len(Graph.nodes())):
OFV += ModularityMatrix[i, j] * (1 - x[(i, j)])
model.setObjective(OFV, GRB.MAXIMIZE)
for [i, j, k] in list_of_cut_triads:
model.addConstr(x[(i, k)] <= x[(i, j)] + x[(j, k)], 'triangle1' + ',' + str(i) + ',' + str(j) + ',' + str(k))
model.addConstr(x[(i, j)] <= x[(i, k)] + x[(j, k)], 'triangle2' + ',' + str(i) + ',' + str(j) + ',' + str(k))
model.addConstr(x[(j, k)] <= x[(i, j)] + x[(i, k)], 'triangle3' + ',' + str(i) + ',' + str(j) + ',' + str(k))
formulation_time = time.time() - formulation_time_start
model.update()
# Using a warm start
# A known partition can be used as a starting point to "warm-start" the algorithm.
# It can be provided to the model here by giving start values to the decision variables:
# If this optional step is skipped, you should comment out these five lines
if warmstart == 1:
# Solution from Combo algorithm to be used as warm-start
partition = pycombo.execute(Graph, modularity_resolution=resolution)
community_combo = convert_to_com_list(partition[0])
for i in (Graph).nodes():
for j in filter(lambda x: x > i, (Graph).nodes()):
if find_in_list_of_list(community_combo, i) == find_in_list_of_list(community_combo, j):
x[(i, j)].start = 0
else:
x[(i, j)].start = 1
# branching priority is based on total degrees of pairs of nodes
if branching_priotiy == 1:
neighbors = {}
Degree = []
for i in range(len(Graph.nodes())):
for j in range(i + 1, len(Graph.nodes())):
neighbors[i] = list((Graph)[i])
neighbors[j] = list((Graph)[j])
Degree.append(len(neighbors[i]) + len(neighbors[j]))
model.setAttr('BranchPriority', model.getVars()[:], Degree)
model.update()
start_time = time.time()
if validinequality:
# Add valid inequalities to the root node.
while 1:
model.optimize()
var_vals = {}
for var in model.getVars():
var_vals[var.varName] = var.x
if is_integer_solution(Graph, var_vals):
break
Cuts = TwoPartitionSeperation(var_vals)
if len(Cuts):
model = AddCuts(model, Cuts)
model.update()
else:
break
else:
model.optimize()
var_vals = {}
for var in model.getVars():
var_vals[var.varName] = var.x
obj = model.getObjective()
solveTime = (time.time() - start_time)
# objectivevalue = np.round(((2*obj.getValue()+(ModularityMatrix.trace()[0,0]))/np.sum(AdjacencyMatrix)), 8)
objectivevalue = np.round(((2 * obj.getValue() + (ModularityMatrix.trace())) / np.sum(AdjacencyMatrix)), 8)
# print('Instance 0',': modularity equals',objectivevalue)
# if (model.NodeCount)**(1/((size)+2*(order))) >= 1:
# effectiveBranchingFactors = ((model.NodeCount)**(1/((size)+2*(order))))
return objectivevalue, var_vals, model, list_of_cut_triads, formulation_time, solveTime
def run_lp(model, Graph, fixed_ones, fixed_zeros, resolution):
"""
Run the LP based on model and the original Graph as input
"""
# ModularityMatrix = nx.modularity_matrix(Graph, weight='actual_weight')
ModularityMatrix = get_modularity_matrix(Graph, resolution)
AdjacencyMatrix = nx.adjacency_matrix(Graph, weight='actual_weight')
for var_name in fixed_ones:
var = model.getVarByName(var_name)
var.setAttr("LB", 1.0)
model.update()
for var_name in fixed_zeros:
var = model.getVarByName(var_name)
var.setAttr("UB", 0.0)
model.update()
start_time = time.time()
model.optimize()
solveTime = (time.time() - start_time)
obj = model.getObjective()
try:
obj_val = obj.getValue()
except AttributeError as error:
return -1, -1, model
objectivevalue = np.round((((2 * obj_val) + (ModularityMatrix.trace())) / np.sum(AdjacencyMatrix)), 8)
var_vals = {}
for var in model.getVars():
var_vals[var.varName] = var.x
return objectivevalue, var_vals, model
def reset_model_varaibles(model, fixed_ones, fixed_zeros):
for var_name in fixed_ones:
var = model.getVarByName(var_name)
var.setAttr("LB", 0.0)
model.update()
for var_name in fixed_zeros:
var = model.getVarByName(var_name)
var.setAttr("UB", 1.0)
model.update()
return model
# In[12]:
def calculate_modularity(community, Graph, resolution):
"""
Method that calculates modularity for input community partition on input Graph
"""
ModularityMatrix = get_modularity_matrix(Graph, resolution)
AdjacencyMatrix = nx.adjacency_matrix(Graph, weight="actual_weight")
OFV = 0
for item in community:
if len(item) > 1:
for i in range(0, len(item)):
for j in range(i + 1, len(item)):
OFV = OFV + 2 * (ModularityMatrix[item[i], item[j]])
# OFV = OFV + ModularityMatrix.trace()[0,0]
OFV = OFV + ModularityMatrix.trace()
return np.round(OFV / (np.sum(AdjacencyMatrix)), 8)
def calculate_weighted_modularity(community, Graph, resolution):
"""
Method that calculates weighted modularity for input community partition on input Graph
"""
ModularityMatrix = get_weighted_modularity_matrix(Graph, resolution, weight="weight")
AdjacencyMatrix = nx.adjacency_matrix(Graph, weight="weight")
OFV = 0
for item in community:
if len(item) > 1:
for i in range(0, len(item)):
for j in range(i + 1, len(item)):
OFV = OFV + 2 * (ModularityMatrix[item[i], item[j]])
# OFV = OFV + ModularityMatrix.trace()[0,0]
OFV = OFV + ModularityMatrix.trace()
return np.round(OFV / (np.sum(AdjacencyMatrix)), 8)
def find_violating_triples(Graph, var_vals, list_of_cut_triads):
"""
Returns a dictionary whose key is a violated constrained and value is the sum
"""
violated_triples_sums = {}
# list_of_tuples=list(combinations(np.sort(list((Graph).nodes())),3))
# list_of_triads=[list(elem) for elem in list_of_tuples]
for [i, j, k] in list_of_cut_triads:
triple_sum = var_vals[str(i) + "," + str(j)] + var_vals[str(j) + "," + str(k)] + var_vals[str(i) + "," + str(k)]
if 0 < triple_sum < 2:
violated_triples_sums[(i, j, k)] = triple_sum
return violated_triples_sums
def get_best_triple(violated_triples_sums, node, orig_g):
"""
Returns the constraint with the most in common with the previous nodes constraint
"""
# best_triple = (-1, -1, -1)
# if node.constraints == []:
# return list(violated_triples_sums.keys())[0]
# previous = node.constraints[-1]
# current_best = -1
# for triple in violated_triples_sums.keys():
# count = 0
# if triple[0] in previous:
# count += 1
# if triple[1] in previous:
# count += 1
# if triple[2] in previous:
# count += 1
# variables = [str(triple[0])+","+str(triple[1]), str(triple[0])+","+str(triple[2]), str(triple[1])+","+str(triple[2])]
# new_count = 0
# for var in variables:
# if var in node.get_fixed_ones() or var in node.get_fixed_zeros():
# new_count += 1
# if new_count == 3:
# continue
# else:
# count += new_count
# if count > current_best:
# current_best = count
# best_triple = (triple[0], triple[1], triple[2])
# if current_best == 5:
# return best_triple
# return best_triple
num_nodes = len(list(orig_g.nodes()))
score_list = []
violated_triples = list(violated_triples_sums.keys())
for triple in violated_triples:
new_triple = [-1, -1, -1]
value_zero = orig_g.nodes[triple[0]]['super node of'][0]
value_one = orig_g.nodes[triple[1]]['super node of'][0]
value_two = orig_g.nodes[triple[2]]['super node of'][0]
for n in node.graph.nodes():
if value_zero in node.graph.nodes[n]["super node of"]:
new_triple[0] = n
if value_one in node.graph.nodes[n]["super node of"]:
new_triple[1] = n
if value_two in node.graph.nodes[n]["super node of"]:
new_triple[2] = n
if new_triple[0] != -1 and new_triple[1] != -1 and new_triple[2] != -1:
break
total_score = 0
for t in range(3):
alpha = 0
for i in range(triple[t] + 1, num_nodes):
variable = str(triple[t]) + "," + str(i)
if variable in node.get_fixed_ones():
alpha += 1
if variable in node.get_fixed_zeros():
alpha += 1
beta = 0
if node.parent is not None:
for constr in node.constraints:
if triple[t] in constr[:3]:
beta += 1
delta = node.graph.degree(new_triple[t], weight="actual_weight")
score = 1 - np.exp(-alpha) + beta + (delta / len(list(node.graph.nodes())))
total_score += score
score_list.append(total_score)
sum_of_scores = np.sum(score_list)
probability_list = [x / sum_of_scores for x in score_list]
index = np.random.choice(len(violated_triples), p=probability_list)
return violated_triples[index][:3]
def is_integer_solution(Graph, var_vals):
"""
Return whether all the varaible values are integer
"""
for i in range(len(Graph.nodes())):
for j in range(i + 1, len(Graph.nodes())):
if var_vals[str(i) + "," + str(j)] != 1 and var_vals[str(i) + "," + str(j)] != 0:
return False
return True
def reduce_triple(G, triple, orig_g, resolution):
"""
Reduces G by creating a supernode for nodes in triple (for left branching).
Returns the reduced graph and the additional edges added for running combo
"""
new_triple = [-1, -1, -1]
# for node in G.nodes():
# if triple[0] in G.nodes[node]["super node of"]:
# new_triple[0] = node
# if triple[1] in G.nodes[node]["super node of"]:
# new_triple[1] = node
# if triple[2] in G.nodes[node]["super node of"]:
# new_triple[2] = node
# triple = new_triple
value_zero = orig_g.nodes[triple[0]]['super node of'][0]
value_one = orig_g.nodes[triple[1]]['super node of'][0]
value_two = orig_g.nodes[triple[2]]['super node of'][0]
for node in G.nodes():
if value_zero in G.nodes[node]["super node of"]:
new_triple[0] = node
if value_one in G.nodes[node]["super node of"]:
new_triple[1] = node
if value_two in G.nodes[node]["super node of"]:
new_triple[2] = node
triple = new_triple
# print("TRIPLE: " + str(triple))
Graph = G.copy()
self_weight = 0
for u in range(3):
for v in range(u, 3):
if Graph.has_edge(triple[u], triple[v]):
if 'actual_weight' in Graph.edges[triple[u], triple[v]]:
self_weight += Graph.edges[triple[u], triple[v]]["actual_weight"]
else:
self_weight += 1
if Graph.has_edge(triple[0], triple[0]):
Graph.edges[triple[0], triple[0]]["actual_weight"] = self_weight
curr = Graph.nodes[triple[0]]['super node of']
new1 = Graph.nodes[triple[1]]['super node of']
new2 = Graph.nodes[triple[2]]['super node of']
super_list = list(set(curr + new1 + new2))
super_list.sort()
Graph.nodes[triple[0]]['super node of'] = super_list
else:
Graph.add_edge(triple[0], triple[0])
Graph.edges[triple[0], triple[0]]["actual_weight"] = self_weight
Graph.edges[triple[0], triple[0]]['constrained_modularity'] = False
curr = Graph.nodes[triple[0]]['super node of']
new1 = Graph.nodes[triple[1]]['super node of']
new2 = Graph.nodes[triple[2]]['super node of']
super_list = list(set(curr + new1 + new2))
super_list.sort()
Graph.nodes[triple[0]]['super node of'] = super_list
if triple[0] != triple[1]:
edge_list = list(Graph.edges(triple[1]))
for edge in edge_list:
if edge[1] not in [triple[0], triple[2]]:
if Graph.has_edge(triple[0], edge[1]):
Graph.edges[triple[0], edge[1]]['actual_weight'] += Graph.edges[edge]['actual_weight']
else:
Graph.add_edge(triple[0], edge[1])
Graph.edges[triple[0], edge[1]]['actual_weight'] = Graph.edges[edge]['actual_weight']
Graph.edges[triple[0], edge[1]]['constrained_modularity'] = False
Graph.remove_node(triple[1])
if triple[0] != triple[2] and triple[1] != triple[2]:
edge_list = list(Graph.edges(triple[2]))
for edge in edge_list:
if edge[1] not in [triple[0], triple[1]]:
if Graph.has_edge(triple[0], edge[1]):
Graph.edges[triple[0], edge[1]]['actual_weight'] += Graph.edges[edge]['actual_weight']
else:
Graph.add_edge(triple[0], edge[1])
Graph.edges[triple[0], edge[1]]['actual_weight'] = Graph.edges[edge]['actual_weight']
Graph.edges[triple[0], edge[1]]['constrained_modularity'] = False
Graph.remove_node(triple[2])
Graph = nx.convert_node_labels_to_integers(Graph)
edges_added = []
# ModularityMatrix = nx.modularity_matrix(Graph, weight="actual_weight")
ModularityMatrix = get_modularity_matrix(Graph, resolution)
for i in range(ModularityMatrix.shape[0]):
for j in range(i, ModularityMatrix.shape[0]):
if Graph.has_edge(i, j):
if Graph.edges[(i, j)]['constrained_modularity']:
Graph.edges[(i, j)]['weight'] = max(-1, ModularityMatrix[i, j] - 0.5)
else:
Graph.edges[(i, j)]['weight'] = ModularityMatrix[i, j]
else:
Graph.add_edge(i, j)
Graph.edges[(i, j)]['weight'] = ModularityMatrix[i, j]
Graph.edges[(i, j)]['constrained_modularity'] = False
edges_added.append((i, j))
return Graph, edges_added
def alter_modularity(G, triple, orig_g, delta, resolution):
"""
Alter the modularity associated with nodes in triple by input factor (for right branching).
Returns the reduced graph and additional edges added for running pycombo
"""
new_triple = [-1, -1, -1]
value_zero = orig_g.nodes[triple[0]]['super node of'][0]
value_one = orig_g.nodes[triple[1]]['super node of'][0]
value_two = orig_g.nodes[triple[2]]['super node of'][0]
for node in G.nodes():
if value_zero in G.nodes[node]["super node of"]:
new_triple[0] = node
if value_one in G.nodes[node]["super node of"]:
new_triple[1] = node
if value_two in G.nodes[node]["super node of"]:
new_triple[2] = node
triple = new_triple
# ModularityMatrix = nx.modularity_matrix(G, weight="actual_weight")
Graph = G.copy()
edges_added = []
# ModularityMatrix = nx.modularity_matrix(Graph, weight="actual_weight")
ModularityMatrix = get_modularity_matrix(Graph, resolution)
for i in range(ModularityMatrix.shape[0]):
for j in range(i, ModularityMatrix.shape[0]):
if (i, j) in [(triple[0], triple[1]), (triple[0], triple[2]), (triple[1], triple[2]),
(triple[1], triple[0]), (triple[2], triple[0]), (triple[2], triple[1])] and Graph.has_edge(i,
j):
Graph.edges[(i, j)]['weight'] = max(-1,
ModularityMatrix[i, j] - delta) # replace with max(-1, orig- 0.5)
Graph.edges[(i, j)]['constrained_modularity'] = True
elif Graph.has_edge(i, j):
Graph.edges[(i, j)]['weight'] = ModularityMatrix[i, j]
Graph.edges[(i, j)]['constrained_modularity'] = False
else:
Graph.add_edge(i, j)
Graph.edges[(i, j)]['weight'] = ModularityMatrix[i, j]
Graph.edges[(i, j)]['constrained_modularity'] = False
edges_added.append((i, j))
return Graph, edges_added
def remove_extra_edges(Graph, edge_list):
"""
Removes the additional edges added for running pycombo
"""
for edge in edge_list:
Graph.remove_edge(edge[0], edge[1])
return Graph
def reduced_cost_variable_fixing(model, var_vals, obj_value, lower_bound, Graph, resolution):
AdjacencyMatrix = nx.adjacency_matrix(Graph, weight="actual_weight")
ModularityMatrix = get_modularity_matrix(Graph, resolution)
# new_obj_val = ((obj_value*np.sum(AdjacencyMatrix)) - ModularityMatrix.trace()[0, 0])/2
# new_lower_bound = ((lower_bound*np.sum(AdjacencyMatrix)) - ModularityMatrix.trace()[0, 0])/2
new_obj_val = ((obj_value * np.sum(AdjacencyMatrix)) - ModularityMatrix.trace()) / 2
new_lower_bound = ((lower_bound * np.sum(AdjacencyMatrix)) - ModularityMatrix.trace()) / 2
vars_one = []
vars_zero = []
for key in var_vals.keys():
var = model.getVarByName(key)
if var_vals[key] == 1:
if new_obj_val - var.getAttr(GRB.Attr.RC) < new_lower_bound:
vars_one.append(key)
elif var_vals[key] == 0:
if new_obj_val + var.getAttr(GRB.Attr.RC) < new_lower_bound:
vars_zero.append(key)
return vars_one, vars_zero
class Node:
"""
Represents one node in the bayan tree
"""