generated from dscoool/mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
1367 lines (1023 loc) · 41.6 KB
/
graph.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
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 15:44:57 2018
@author: Administrator
"""
import numpy as np
import random as rd
import copy
# In[1]:
#graph adt
class graph:
"""Graph ADT"""
def __init__(self):
self.graph={}
self.visited={}
def append(self,vertexid,edge,weight):
"""add/update new vertex,edge,weight"""
if vertexid not in self.graph.keys():
self.graph[vertexid]={}
self.visited[vertexid]=0
if edge not in self.graph.keys():
self.graph[edge]={}
self.visited[edge]=0
self.graph[vertexid][edge]=weight
def reveal(self):
"""return adjacent list"""
return self.graph
def vertex(self):
"""return all vertices in the graph"""
return list(self.graph.keys())
def edge(self,vertexid):
"""return edge of a particular vertex"""
return list(self.graph[vertexid].keys())
def edge_reverse(self,vertexid):
"""return vertices directing to a particular vertex"""
return [i for i in self.graph if vertexid in self.graph[i]]
def weight(self,vertexid,edge):
"""return weight of a particular vertex"""
return (self.graph[vertexid][edge])
def order(self):
"""return number of vertices"""
return len(self.graph)
def visit(self,vertexid):
"""visit a particular vertex"""
self.visited[vertexid]=1
def go(self,vertexid):
"""return the status of a particular vertex"""
return self.visited[vertexid]
def route(self):
"""return which vertices have been visited"""
return self.visited
def degree(self,vertexid):
"""return degree of a particular vertex"""
return len(self.graph[vertexid])
def mat(self):
"""return adjacent matrix"""
self.matrix=[[0 for _ in range(max(self.graph.keys())+1)] for i in range(max(self.graph.keys())+1)]
for i in self.graph:
for j in self.graph[i].keys():
self.matrix[i][j]=1
return self.matrix
def remove(self,vertexid):
"""remove a particular vertex and its underlying edges"""
for i in self.graph[vertexid].keys():
self.graph[i].pop(vertexid)
self.graph.pop(vertexid)
def disconnect(self,vertexid,edge):
"""remove a particular edge"""
del self.graph[vertexid][edge]
def clear(self,vertexid=None,whole=False):
"""unvisit a particular vertex"""
if whole:
self.visited=dict(zip(self.graph.keys(),[0 for i in range(len(self.graph))]))
elif vertexid:
self.visited[vertexid]=0
else:
assert False,"arguments must satisfy whole=True or vertexid=int number"
# In[2]:
#algorithms
#
def bfs(ADT,current):
"""Breadth First Search"""
#create a queue with rule of first-in-first-out
queue=[]
queue.append(current)
while queue:
#keep track of the visited vertices
current=queue.pop(0)
ADT.visit(current)
for newpos in ADT.edge(current):
#visit each vertex once
if ADT.go(newpos)==0 and newpos not in queue:
queue.append(newpos)
#
def bidir_bfs(ADT,start,end):
"""Bidirectional Breadth First Search"""
#create queues with rule of first-in-first-out
#queue1 for bfs from start
#queue2 for bfs from end
queue1=[]
queue1.append(start)
queue2=[]
queue2.append(end)
visited1=[]
visited2=[]
while queue1 or queue2:
#keep track of the visited vertices
if queue1:
current1=queue1.pop(0)
visited1.append(current1)
ADT.visit(current1)
if queue2:
current2=queue2.pop(0)
visited2.append(current2)
ADT.visit(current2)
#intersection of two trees
stop=False
for i in ADT.vertex():
if i in visited1 and i in visited2:
stop=True
break
if stop:
break
#do not revisit a vertex
for newpos in ADT.edge(current1):
if newpos not in visited1 and newpos not in queue1:
queue1.append(newpos)
for newpos in ADT.edge(current2):
if newpos not in visited2 and newpos not in queue2:
queue2.append(newpos)
#
def dfs_itr(ADT,current):
"""Depth First Search without Recursion"""
queue=[]
queue.append(current)
#the loop is the backtracking part when it reaches cul-de-sac
while queue:
#keep track of the visited vertices
current=queue.pop(0)
ADT.visit(current)
#priority queue
smallq=[]
#find children and add to the priority
for newpos in ADT.edge(current):
if ADT.go(newpos)==0:
#if the child vertex has already been in queue
#move it to the frontline of queue
if newpos in queue:
queue.remove(newpos)
smallq.append(newpos)
queue=smallq+queue
#
def dfs(ADT,current):
"""Depth First Search"""
#keep track of the visited vertices
ADT.visit(current)
#the loop is the backtracking part when it reaches cul-de-sac
for newpos in ADT.edge(current):
#if the vertex hasnt been visited
#we call dfs recursively
if ADT.go(newpos)==0:
dfs(ADT,newpos)
#
def dfs_topo_sort(ADT,current):
"""Topological sort powered by recursive DFS to get linear ordering"""
#keep track of the visited vertices
ADT.visit(current)
yield current
#the loop is the backtracking part when it reaches cul-de-sac
for newpos in ADT.edge(current):
#if the vertex hasnt been visited
#we call dfs recursively
if ADT.go(newpos)==0:
yield from dfs_topo_sort(ADT,newpos)
#
def kahn(ADT):
"""Topological sort powered by Kahn's Algorithm"""
#find all edges
edges=[]
for i in ADT.vertex():
for j in ADT.edge(i):
edges.append((i,j))
#find vertices with zero in-degree
start=[i[0] for i in edges]
end=[i[1] for i in edges]
queue=set(start).difference(set(end))
#in-degree for every vertex
in_degree={}
for i in set(end):
in_degree[i]=end.count(i)
result=[]
while queue:
#pop a random vertex with zero in-degree
current=queue.pop()
result.append(current)
#check its neighbors
for i in ADT.edge(current):
#update their in-degree
in_degree[i]-=1
#add vertices with zero in-degree into the queue
if in_degree[i]==0:
queue.add(i)
return result
#
def bfs_path(ADT,start,end):
"""Breadth First Search to find the path from start to end"""
#create a queue with rule of first-in-first-out
queue=[]
queue.append(start)
#pred keeps track of how we get to the current vertex
pred={}
while queue:
#keep track of the visited vertices
current=queue.pop(0)
ADT.visit(current)
for newpos in ADT.edge(current):
#visit each vertex once
if ADT.go(newpos)==0 and newpos not in queue:
queue.append(newpos)
pred[newpos]=current
#traversal ends when the target is met
if current==end:
break
#create the path by backtracking
#trace the predecessor vertex from end to start
previous=end
path=[]
while pred:
path.insert(0, previous)
if previous==start:
break
previous=pred[previous]
#note that if we cant go from start to end
#we may get inf for distance
#additionally, the path may not include start position
return len(path)-1,path
#
def bidir_bfs_path(ADT,start,end):
"""Bidirectional Breadth First Search to find the path from start to end"""
#create queues with rule of first-in-first-out
#queue1 for bfs from start
#queue2 for bfs from end
queue1=[]
queue1.append(start)
queue2=[]
queue2.append(end)
visited1=[]
visited2=[]
#pred keeps track of how we get to the current vertex
pred={}
while queue1 or queue2:
#keep track of the visited vertices
if queue1:
current1=queue1.pop(0)
visited1.append(current1)
if queue2:
current2=queue2.pop(0)
visited2.append(current2)
#intersection of two trees
stop=False
for i in ADT.vertex():
if i in visited1 and i in visited2:
stop=True
break
if stop:
break
#do not revisit a vertex
for newpos1 in ADT.edge(current1):
if newpos1 not in visited1 and newpos1 not in queue1:
queue1.append(newpos1)
if newpos1 in pred:
pred[current1]=newpos1
else:
pred[newpos1]=current1
for newpos2 in ADT.edge(current2):
if newpos2 not in visited2 and newpos2 not in queue2:
queue2.append(newpos2)
if newpos2 in pred:
pred[current2]=newpos2
else:
pred[newpos2]=current2
#create the path by backtracking
#trace the predecessor vertex from end to start
previous=end
path=[]
while pred:
path.insert(0, previous)
if previous==start:
break
previous=pred[previous]
#note that if we cant go from start to end
#we may get inf for distance
#additionally, the path may not include start position
return len(path)-1,path
#
def dfs_path(ADT,start,end):
"""Depth First Search to find the path from start to end"""
queue=[]
queue.append(start)
#pred keeps track of how we get to the current vertex
pred={}
#the loop is the backtracking part when it reaches cul-de-sac
while queue:
#keep track of the visited vertices
current=queue.pop(0)
ADT.visit(current)
#priority queue
smallq=[]
#find children and add to the priority
for newpos in ADT.edge(current):
if ADT.go(newpos)==0:
#if the child vertex has already been in queue
#move it to the frontline of queue
if newpos in queue:
queue.remove(newpos)
smallq.append(newpos)
pred[newpos]=current
queue=smallq+queue
#traversal ends when the target is met
if current==end:
break
#create the path by backtracking
#trace the predecessor vertex from end to start
previous=end
path=[]
while pred:
path.insert(0, previous)
if previous==start:
break
previous=pred[previous]
#note that if we cant go from start to end
#we may get inf for distance
#additionally, the path may not include start position
return len(path)-1,path
#
def dijkstra(ADT,start,end):
"""Dijkstra's Algorithm to find the shortest path"""
#all weights in dcg must be positive
#otherwise we have to use bellman ford instead
neg_check=[j for i in ADT.reveal() for j in ADT.reveal()[i].values()]
assert min(neg_check)>=0,"negative weights are not allowed, please use Bellman-Ford"
#queue is used to check the vertex with the minimum weight
queue={}
queue[start]=0
#distance keeps track of distance from starting vertex to any vertex
distance={}
for i in ADT.vertex():
distance[i]=float('inf')
distance[start]=0
#pred keeps track of how we get to the current vertex
pred={}
#dynamic programming
while queue:
#vertex with the minimum weight in queue
current=min(queue,key=queue.get)
queue.pop(current)
for j in ADT.edge(current):
#check if the current vertex can construct the optimal path
if distance[current]+ADT.weight(current,j)<distance[j]:
distance[j]=distance[current]+ADT.weight(current,j)
pred[j]=current
#add child vertex to the queue
if ADT.go(j)==0 and j not in queue:
queue[j]=distance[j]
#each vertex is visited only once
ADT.visit(current)
#traversal ends when the target is met
if current==end:
break
#create the shortest path by backtracking
#trace the predecessor vertex from end to start
previous=end
path=[]
while pred:
path.insert(0, previous)
if previous==start:
break
previous=pred[previous]
#note that if we cant go from start to end
#we may get inf for distance[end]
#additionally, the path may not include start position
return distance[end],path
#
def bellman_ford(ADT,start,end):
"""Bellman-Ford Algorithm,
a modified Dijkstra's algorithm to detect negative cycle"""
#distance keeps track of distance from starting vertex to any vertex
distance={}
for i in ADT.vertex():
distance[i]=float('inf')
distance[start]=0
#pred keeps track of how we get to the current vertex
pred={}
#dynamic programming
for _ in range(1,ADT.order()-1):
for i in ADT.vertex():
for j in ADT.edge(i):
try:
if distance[i]+ADT.weight(i,j)<distance[j]:
distance[j]=distance[i]+ADT.weight(i,j)
pred[j]=i
except KeyError:
pass
#detect negative cycle
for k in ADT.vertex():
for l in ADT.edge(k):
try:
assert distance[k]+ADT.weight(k,l)>=distance[l],'negative cycle exists!'
except KeyError:
pass
#create the shortest path by backtracking
#trace the predecessor vertex from end to start
previous=end
path=[]
while pred:
path.insert(0, previous)
if previous==start:
break
previous=pred[previous]
return distance[end],path
#
def a_star(ADT,start,end):
"""A* Algorithm,
a generalized Dijkstra's algorithm with heuristic function to reduce execution time"""
#all weights in dcg must be positive
#otherwise we have to use bellman ford instead
neg_check=[j for i in ADT.reveal() for j in ADT.reveal()[i].values()]
assert min(neg_check)>=0,"negative weights are not allowed, please use Bellman-Ford"
#queue is used to check the vertex with the minimum summation
queue={}
queue[start]=0
#distance keeps track of distance from starting vertex to any vertex
distance={}
#heuristic keeps track of distance from ending vertex to any vertex
heuristic={}
#route is a dict of the summation of distance and heuristic
route={}
#criteria
for i in ADT.vertex():
#initialize
distance[i]=float('inf')
#manhattan distance
heuristic[i]=abs(i[0]-end[0])+abs(i[1]-end[1])
#initialize
distance[start]=0
#pred keeps track of how we get to the current vertex
pred={}
#dynamic programming
while queue:
#vertex with the minimum summation
current=min(queue,key=queue.get)
queue.pop(current)
#find the minimum summation of both distances
minimum=float('inf')
for j in ADT.edge(current):
#check if the current vertex can construct the optimal path
#from the beginning and to the end
distance[j]=distance[current]+ADT.weight(current,j)
route[j]=distance[j]+heuristic[j]
if route[j]<minimum:
minimum=route[j]
for j in ADT.edge(current):
#only append unvisited and unqueued vertices
if (route[j]==minimum) and (ADT.go(j)==0) and (j not in queue):
queue[j]=route[j]
pred[j]=current
#each vertex is visited only once
ADT.visit(current)
#traversal ends when the target is met
if current==end:
break
#create the shortest path by backtracking
#trace the predecessor vertex from end to start
previous=end
path=[]
while pred:
path.insert(0, previous)
if previous==start:
break
previous=pred[previous]
#note that if we cant go from start to end
#we may get inf for distance[end]
#additionally, the path may not include start position
return distance[end],path
#
def prim(ADT,start):
"""Prim's Algorithm to find a minimum spanning tree"""
#initialize
queue={}
queue[start]=0
#route keeps track of how we travel from one vertex to another
route={}
route[start]=start
#result is a list that keeps the order of vertices we have visited
result=[]
#pop the edge with the smallest weight
while queue:
#note that when we have two vertices with the same minimum weights
#the dictionary would pop the one with the smallest key
current=min(queue,key=queue.get)
queue.pop(current)
result.append(current)
ADT.visit(current)
#BFS
for i in ADT.edge(current):
if i not in queue and ADT.go(i)==0:
queue[i]=ADT.weight(current,i)
route[i]=current
#every time we find a smaller weight
#we need to update the smaller weight in queue
if i in queue and queue[i]>ADT.weight(current,i):
queue[i]=ADT.weight(current,i)
route[i]=current
#create minimum spanning tree
subset=graph()
for i in result:
if i!=start:
subset.append(route[i],i,ADT.weight(route[i],i))
subset.append(i,route[i],ADT.weight(route[i],i))
return subset
#
def trace_root(disjointset,target):
"""Use recursion to trace root in a disjoint set"""
if disjointset[target]!=target:
trace_root(disjointset,disjointset[target])
else:
return target
#
def kruskal(ADT):
"""Kruskal's Algorithm to find the minimum spanning tree"""
#use dictionary to sort edges by weight
D={}
for i in ADT.vertex():
for j in ADT.edge(i):
#get all edges
if f'{j}-{i}' not in D.keys():
D[f'{i}-{j}']=ADT.weight(i,j)
sort_edge_by_weight=sorted(D.items(), key=lambda x:x[1])
result=[]
#use disjointset to detect cycle
disjointset={}
for i in ADT.vertex():
disjointset[i]=i
for i in sort_edge_by_weight:
parent=int(i[0].split('-')[0])
child=int(i[0].split('-')[1])
#first check disjoint set
#if it already has indicated cycle
#trace_root function will go to infinite loops
if disjointset[parent]!=disjointset[child]:
#if we trace back to the root of the tree
#and it indicates no cycle
#we update the disjoint set and add edge into result
if trace_root(disjointset,parent)!=trace_root(disjointset,child):
disjointset[child]=parent
result.append([parent,child])
#create minimum spanning tree
subset=graph()
for i in result:
subset.append(i[0],i[1],ADT.weight(i[0],i[1]))
subset.append(i[1],i[0],ADT.weight(i[0],i[1]))
return subset
#
def boruvka(ADT):
"""Borůvka's Algorithm to find the minimum spanning tree"""
subset=graph()
#get the edge with minimum weight for each vertex
for i in ADT.vertex():
minimum=float('inf')
target=None
for j in ADT.edge(i):
if ADT.weight(i,j)<minimum:
minimum=ADT.weight(i,j)
target=[i,j]
#append both edges as the graph is undirected
subset.append(target[0],target[1],ADT.weight(target[0],target[1]))
subset.append(target[1],target[0],ADT.weight(target[0],target[1]))
#use dfs topological sort to find connected components
connected_components=[]
for i in subset.vertex():
#avoid duplicates of connected components
#use jump to break out of multiple loops
jump=False
for j in connected_components:
if i in j:
jump=True
break
if jump:
continue
connected_components.append(list(dfs_topo_sort(subset,i)))
#connect 2 connected components with minimum weight
#same logic as the first iteration
for i in range(len(connected_components)):
for j in range(i+1,len(connected_components)):
minimum=float('inf')
target=None
for k in connected_components[i]:
for l in ADT.edge(k):
if l in connected_components[j]:
if ADT.weight(k,l)<minimum:
minimum=ADT.weight(k,l)
target=[k,l]
subset.append(target[0],target[1],minimum)
subset.append(target[1],target[0],minimum)
return subset
#
def get_degree_list(ADT):
"""create degree distribution"""
D={}
#if the current degree hasnt been checked
#we create a new key under the current degree
#otherwise we append the new node into the list
for i in ADT.vertex():
try:
D[ADT.degree(i)].append(i)
except KeyError:
D[ADT.degree(i)]=[i]
#dictionary is sorted by key instead of value in ascending order
D=dict(sorted(D.items()))
return D
#
def matula_beck(ADT,ordering=False,degeneracy=False):
"""An algorithm proposed by David W. Matula, and Leland L. Beck to find k core of a graph ADT.
The implementation is based upon their original paper called
"Smallest-last ordering and clustering and graph coloring algorithms".
"""
subset=copy.deepcopy(ADT)
#k is the ultimate degeneracy
k=0
#denote L as the checked list
L=[]
#denote output as the storage of vertices in 1-core to k-core
output={}
#degree distribution
D=get_degree_list(subset)
#initialize
for i in range(1,max(D.keys())):
output[i]=[]
#we initialize the current degree i to 0
#because we want to keep track of 1-core to k-core
i=0
while D:
#denote i as the minimum degree in the current graph
i=list(D.keys())[0]
#k denotes the degeneracy
k=max(k,i)
#pick a random vertex with the minimum degree
v=D[i].pop(0)
#checked and removed
L.append(v)
subset.remove(v)
output[k].append(v)
#update the degree list
D=get_degree_list(subset)
#start from -2 to 0
for ind in sorted(output.keys(),reverse=True)[1:]:
#remove empty k-core
if not output[ind+1]:
del output[ind+1]
#add vertices from high order core to low order core
else:
output[ind]+=output[ind+1]
#output depends on the requirement
if ordering:
return L
elif degeneracy:
return k
else:
return output
#
def sort_by_degree(ADT):
"""sort vertices by degree"""
dic={}
for i in ADT.vertex():
dic[i]=ADT.degree(i)
#the dictionary is sorted by value and exported as a list in descending order
output=[i[0] for i in sorted(dic.items(), key=lambda x:x[1])]
return output[::-1]
#
def batagelj_zaversnik(k,ADT):
"""An algorithm proposed by Vladimir Batagelj and Matjaž Zaveršnik to find k core of a graph ADT.
The implementation is based upon their original paper called
"An O(m) Algorithm for Cores Decomposition of Networks".
"""
subset=copy.deepcopy(ADT)
#denote D as a dictionary
#where the key is the vertex
#the value is its degree
D={}
for i in subset.vertex():
D[i]=subset.degree(i)
#denote queue as a sorted list of vertices by descending degree
queue=sort_by_degree(subset)
while queue:
#each iteration, we extract the vertex with the minimum degree from the queue
#we mark each vertex we examine in the graph structure
i=queue.pop()
subset.visit(i)
#if the current degree is smaller than our target k
#we introduce penalty to its adjacent vertices
if D[i]<k:
for j in subset.edge(i):
D[j]-=1
#update the queue with the latest degree
#exclude all the marked vertices
#the queue should always be in descending order
queue=[]
for key,_ in sorted(D.items(),reverse=True,key=lambda x:x[1]):
if subset.go(key)==0:
queue.append(key)
#after the size of the queue shrinks to zero
#any vertex with degree not smaller than k will go into k core
return [i for i in D if D[i]>=k]
#
def bron_kerbosch(ADT,R=set(),P=set(),X=set()):
"""Bron Kerbosch algorithm to find maximal cliques
P stands for priority queue, where pending vertices are
R stands for result set, X stands for checked list
To find maximal cliques, only P is required to be filled
P=set(ADT.vertex())"""
#when we have nothing left in the priority queue and checked list
#we find a maximal clique
if not P and not X:
yield R
#while we still got vertices in priority queue
#we pick a random adjacent vertex and add into the clique
while P:
v=P.pop()
yield from bron_kerbosch(ADT,
#add a new adjacent vertex into the result set
#trying to expand the clique to the maximal
R=R.union([v]),
#the priority queue is bounded by the rule of adjacency
#a vertex can be added into the priority queue
#if and only if it is neighbor to everyone in the current clique
P=P.intersection(ADT.edge(v)),
#the checked list is bounded by the rule of adjacency as well
X=X.intersection(ADT.edge(v)))
#the vertex has been checked
X.add(v)
#
def bron_kerbosch_pivot(ADT,R=set(),P=set(),X=set()):
"""Bron Kerbosch algorithm with pivoting to find maximal cliques
P stands for priority queue, where pending vertices are
R stands for result set, X stands for checked list
To find maximal cliques, only P is required to be filled
P=set(ADT.vertex())"""
if not P and not X:
yield R
#choose a pivot vertex u from the union of pending and processed vertices
#delay the neighbors of pivot vertex from being added to the clique to reduce recursive calls
try:
u=list(P.union(X)).pop()
N=P.difference(ADT.edge(u))
#if the neighbors of pivot u are equivalent to priority queue
#in that case we just roll back to the function without pivoting