forked from soniakeys/graph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
undir_cg.go
1138 lines (1103 loc) · 31.7 KB
/
undir_cg.go
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
// Copyright 2014 Sonia Keys
// License MIT: http://opensource.org/licenses/MIT
package graph
import (
"errors"
"fmt"
"github.com/soniakeys/bits"
)
// undir_RO.go is code generated from undir_cg.go by directives in graph.go.
// Editing undir_cg.go is okay. It is the code generation source.
// DO NOT EDIT undir_RO.go.
// The RO means read only and it is upper case RO to slow you down a bit
// in case you start to edit the file.
//-------------------
// Bipartite constructs an object indexing the bipartite structure of a graph.
//
// In a bipartite component, nodes can be partitioned into two sets, or
// "colors," such that every edge in the component goes from one set to the
// other.
//
// If the graph is bipartite, the method constructs and returns a new
// Bipartite object as b and returns ok = true.
//
// If the component is not bipartite, a representative odd cycle as oc and
// returns ok = false.
//
// In the case of a graph with mulitiple connected components, this method
// provides no control over the color orientation by component. See
// Undirected.BipartiteComponent if this control is needed.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) Bipartite() (b *LabeledBipartite, oc []NI, ok bool) {
c1 := bits.New(g.Order())
c2 := bits.New(g.Order())
r, _, _ := g.ConnectedComponentReps()
// accumulate n2 number of zero bits in c2 as number of one bits in n1
var n, n2 int
for _, r := range r {
ok, n, _, oc = g.BipartiteComponent(r, c1, c2)
if !ok {
return
}
n2 += n
}
return &LabeledBipartite{g, c2, n2}, nil, true
}
// BipartiteComponent analyzes the bipartite structure of a connected component
// of an undirected graph.
//
// In a bipartite component, nodes can be partitioned into two sets, or
// "colors," such that every edge in the component goes from one set to the
// other.
//
// Argument n can be any representative node of the component to be analyzed.
// Arguments c1 and c2 must be separate bits.Bits objects constructed to be
// of length of the number of nodes of g. These bitmaps are used in the
// component traversal and the bits of the component must be zero when the
// method is called.
//
// If the component is bipartite, BipartiteComponent populates bitmaps
// c1 and c2 with the two-coloring of the component, always assigning the set
// with representative node n to bitmap c1. It returns b = true,
// and also returns the number of bits set in c1 and c2 as n1 and n2
// respectively.
//
// If the component is not bipartite, BipartiteComponent returns b = false
// and a representative odd cycle as oc.
//
// See also method Bipartite.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) BipartiteComponent(n NI, c1, c2 bits.Bits) (b bool, n1, n2 int, oc []NI) {
a := g.LabeledAdjacencyList
b = true
var open bool
var df func(n NI, c1, c2 *bits.Bits, n1, n2 *int)
df = func(n NI, c1, c2 *bits.Bits, n1, n2 *int) {
c1.SetBit(int(n), 1)
*n1++
for _, nb := range a[n] {
if c1.Bit(int(nb.To)) == 1 {
b = false
oc = []NI{nb.To, n}
open = true
return
}
if c2.Bit(int(nb.To)) == 1 {
continue
}
df(nb.To, c2, c1, n2, n1)
if b {
continue
}
switch {
case !open:
case n == oc[0]:
open = false
default:
oc = append(oc, n)
}
return
}
}
df(n, &c1, &c2, &n1, &n2)
if b {
return b, n1, n2, nil
}
return b, 0, 0, oc
}
// BronKerbosch1 finds maximal cliques in an undirected graph.
//
// The graph must not contain parallel edges or loops.
//
// See https://en.wikipedia.org/wiki/Clique_(graph_theory) and
// https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm for background.
//
// This method implements the BronKerbosch1 algorithm of WP; that is,
// the original algorithm without improvements.
//
// The method calls the emit argument for each maximal clique in g, as long
// as emit returns true. If emit returns false, BronKerbosch1 returns
// immediately.
//
// There are equivalent labeled and unlabeled versions of this method.
//
// See also more sophisticated variants BronKerbosch2 and BronKerbosch3.
func (g LabeledUndirected) BronKerbosch1(emit func(bits.Bits) bool) {
a := g.LabeledAdjacencyList
var f func(R, P, X bits.Bits) bool
f = func(R, P, X bits.Bits) bool {
switch {
case !P.AllZeros():
r2 := bits.New(len(a))
p2 := bits.New(len(a))
x2 := bits.New(len(a))
pf := func(n int) bool {
r2.Set(R)
r2.SetBit(n, 1)
p2.ClearAll()
x2.ClearAll()
for _, to := range a[n] {
if P.Bit(int(to.To)) == 1 {
p2.SetBit(int(to.To), 1)
}
if X.Bit(int(to.To)) == 1 {
x2.SetBit(int(to.To), 1)
}
}
if !f(r2, p2, x2) {
return false
}
P.SetBit(n, 0)
X.SetBit(n, 1)
return true
}
if !P.IterateOnes(pf) {
return false
}
case X.AllZeros():
return emit(R)
}
return true
}
var R, P, X bits.Bits
R = bits.New(len(a))
P = bits.New(len(a))
X = bits.New(len(a))
P.SetAll()
f(R, P, X)
}
// BKPivotMaxDegree is a strategy for BronKerbosch methods.
//
// To use it, take the method value (see golang.org/ref/spec#Method_values)
// and pass it as the argument to BronKerbosch2 or 3.
//
// The strategy is to pick the node from P or X with the maximum degree
// (number of edges) in g. Note this is a shortcut from evaluating degrees
// in P.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) BKPivotMaxDegree(P, X bits.Bits) (p NI) {
// choose pivot u as highest degree node from P or X
a := g.LabeledAdjacencyList
maxDeg := -1
P.IterateOnes(func(n int) bool { // scan P
if d := len(a[n]); d > maxDeg {
p = NI(n)
maxDeg = d
}
return true
})
X.IterateOnes(func(n int) bool { // scan X
if d := len(a[n]); d > maxDeg {
p = NI(n)
maxDeg = d
}
return true
})
return
}
// BKPivotMinP is a strategy for BronKerbosch methods.
//
// To use it, take the method value (see golang.org/ref/spec#Method_values)
// and pass it as the argument to BronKerbosch2 or 3.
//
// The strategy is to simply pick the first node in P.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) BKPivotMinP(P, X bits.Bits) NI {
return NI(P.OneFrom(0))
}
// BronKerbosch2 finds maximal cliques in an undirected graph.
//
// The graph must not contain parallel edges or loops.
//
// See https://en.wikipedia.org/wiki/Clique_(graph_theory) and
// https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm for background.
//
// This method implements the BronKerbosch2 algorithm of WP; that is,
// the original algorithm plus pivoting.
//
// The argument is a pivot function that must return a node of P or X.
// P is guaranteed to contain at least one node. X is not.
// For example see BKPivotMaxDegree.
//
// The method calls the emit argument for each maximal clique in g, as long
// as emit returns true. If emit returns false, BronKerbosch1 returns
// immediately.
//
// There are equivalent labeled and unlabeled versions of this method.
//
// See also simpler variant BronKerbosch1 and more sophisticated variant
// BronKerbosch3.
func (g LabeledUndirected) BronKerbosch2(pivot func(P, X bits.Bits) NI, emit func(bits.Bits) bool) {
a := g.LabeledAdjacencyList
var f func(R, P, X bits.Bits) bool
f = func(R, P, X bits.Bits) bool {
switch {
case !P.AllZeros():
r2 := bits.New(len(a))
p2 := bits.New(len(a))
x2 := bits.New(len(a))
pnu := bits.New(len(a))
// compute P \ N(u). next 5 lines are only difference from BK1
pnu.Set(P)
for _, to := range a[pivot(P, X)] {
pnu.SetBit(int(to.To), 0)
}
// remaining code like BK1
pf := func(n int) bool {
r2.Set(R)
r2.SetBit(n, 1)
p2.ClearAll()
x2.ClearAll()
for _, to := range a[n] {
if P.Bit(int(to.To)) == 1 {
p2.SetBit(int(to.To), 1)
}
if X.Bit(int(to.To)) == 1 {
x2.SetBit(int(to.To), 1)
}
}
if !f(r2, p2, x2) {
return false
}
P.SetBit(n, 0)
X.SetBit(n, 1)
return true
}
if !pnu.IterateOnes(pf) {
return false
}
case X.AllZeros():
return emit(R)
}
return true
}
R := bits.New(len(a))
P := bits.New(len(a))
X := bits.New(len(a))
P.SetAll()
f(R, P, X)
}
// BronKerbosch3 finds maximal cliques in an undirected graph.
//
// The graph must not contain parallel edges or loops.
//
// See https://en.wikipedia.org/wiki/Clique_(graph_theory) and
// https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm for background.
//
// This method implements the BronKerbosch3 algorithm of WP; that is,
// the original algorithm with pivoting and degeneracy ordering.
//
// The argument is a pivot function that must return a node of P or X.
// P is guaranteed to contain at least one node. X is not.
// For example see BKPivotMaxDegree.
//
// The method calls the emit argument for each maximal clique in g, as long
// as emit returns true. If emit returns false, BronKerbosch1 returns
// immediately.
//
// There are equivalent labeled and unlabeled versions of this method.
//
// See also simpler variants BronKerbosch1 and BronKerbosch2.
func (g LabeledUndirected) BronKerbosch3(pivot func(P, X bits.Bits) NI, emit func(bits.Bits) bool) {
a := g.LabeledAdjacencyList
var f func(R, P, X bits.Bits) bool
f = func(R, P, X bits.Bits) bool {
switch {
case !P.AllZeros():
r2 := bits.New(len(a))
p2 := bits.New(len(a))
x2 := bits.New(len(a))
pnu := bits.New(len(a))
// compute P \ N(u). next lines are only difference from BK1
pnu.Set(P)
for _, to := range a[pivot(P, X)] {
pnu.SetBit(int(to.To), 0)
}
// remaining code like BK2
pf := func(n int) bool {
r2.Set(R)
r2.SetBit(n, 1)
p2.ClearAll()
x2.ClearAll()
for _, to := range a[n] {
if P.Bit(int(to.To)) == 1 {
p2.SetBit(int(to.To), 1)
}
if X.Bit(int(to.To)) == 1 {
x2.SetBit(int(to.To), 1)
}
}
if !f(r2, p2, x2) {
return false
}
P.SetBit(n, 0)
X.SetBit(n, 1)
return true
}
if !pnu.IterateOnes(pf) {
return false
}
case X.AllZeros():
return emit(R)
}
return true
}
R := bits.New(len(a))
P := bits.New(len(a))
X := bits.New(len(a))
P.SetAll()
// code above same as BK2
// code below new to BK3
ord, _ := g.DegeneracyOrdering()
p2 := bits.New(len(a))
x2 := bits.New(len(a))
for _, n := range ord {
R.SetBit(int(n), 1)
p2.ClearAll()
x2.ClearAll()
for _, to := range a[n] {
if P.Bit(int(to.To)) == 1 {
p2.SetBit(int(to.To), 1)
}
if X.Bit(int(to.To)) == 1 {
x2.SetBit(int(to.To), 1)
}
}
if !f(R, p2, x2) {
return
}
R.SetBit(int(n), 0)
P.SetBit(int(n), 0)
X.SetBit(int(n), 1)
}
}
// ConnectedComponentBits returns a function that iterates over connected
// components of g, returning a member bitmap for each.
//
// Each call of the returned function returns the order, arc size,
// and bits of a connected component. The underlying bits allocation is
// the same for each call and is overwritten on subsequent calls. Use or
// save the bits before calling the function again. The function returns
// zeros after returning all connected components.
//
// There are equivalent labeled and unlabeled versions of this method.
//
// See also ConnectedComponentInts, ConnectedComponentReps, and
// ConnectedComponentReps.
func (g LabeledUndirected) ConnectedComponentBits() func() (order, arcSize int, bits bits.Bits) {
a := g.LabeledAdjacencyList
vg := bits.New(len(a)) // nodes visited in graph
vc := bits.New(len(a)) // nodes visited in current component
var order, arcSize int
var df func(NI)
df = func(n NI) {
vg.SetBit(int(n), 1)
vc.SetBit(int(n), 1)
order++
arcSize += len(a[n])
for _, nb := range a[n] {
if vg.Bit(int(nb.To)) == 0 {
df(nb.To)
}
}
return
}
var n int
return func() (o, ma int, b bits.Bits) {
for ; n < len(a); n++ {
if vg.Bit(n) == 0 {
vc.ClearAll()
order, arcSize = 0, 0
df(NI(n))
return order, arcSize, vc
}
}
return // return zeros signalling no more components
}
}
// ConnectedComponenInts returns a list of component numbers (ints) for each
// node of graph g.
//
// The method assigns numbers to components 1-based, 1 through the number of
// components. Return value ci contains the component number for each node.
// Return value nc is the number of components.
//
// There are equivalent labeled and unlabeled versions of this method.
//
// See also ConnectedComponentBits, ConnectedComponentLists, and
// ConnectedComponentReps.
func (g LabeledUndirected) ConnectedComponentInts() (ci []int, nc int) {
a := g.LabeledAdjacencyList
ci = make([]int, len(a))
var df func(NI)
df = func(nd NI) {
ci[nd] = nc
for _, to := range a[nd] {
if ci[to.To] == 0 {
df(to.To)
}
}
return
}
for nd := range a {
if ci[nd] == 0 {
nc++
df(NI(nd))
}
}
return
}
// ConnectedComponentLists returns a function that iterates over connected
// components of g, returning the member list of each.
//
// Each call of the returned function returns a node list of a connected
// component and the arc size of the component. The returned function returns
// nil, 0 after returning all connected components.
//
// There are equivalent labeled and unlabeled versions of this method.
//
// See also ConnectedComponentBits, ConnectedComponentInts, and
// ConnectedComponentReps.
func (g LabeledUndirected) ConnectedComponentLists() func() (nodes []NI, arcSize int) {
a := g.LabeledAdjacencyList
vg := bits.New(len(a)) // nodes visited in graph
var l []NI // accumulated node list of current component
var ma int // accumulated arc size of current component
var df func(NI)
df = func(n NI) {
vg.SetBit(int(n), 1)
l = append(l, n)
ma += len(a[n])
for _, nb := range a[n] {
if vg.Bit(int(nb.To)) == 0 {
df(nb.To)
}
}
return
}
var n int
return func() ([]NI, int) {
for ; n < len(a); n++ {
if vg.Bit(n) == 0 {
l, ma = nil, 0
df(NI(n))
return l, ma
}
}
return nil, 0
}
}
// ConnectedComponentReps returns a representative node from each connected
// component of g.
//
// Returned is a slice with a single representative node from each connected
// component and also parallel slices with the orders and arc sizes
// in the corresponding components.
//
// This is fairly minimal information describing connected components.
// From a representative node, other nodes in the component can be reached
// by depth first traversal for example.
//
// There are equivalent labeled and unlabeled versions of this method.
//
// See also ConnectedComponentBits and ConnectedComponentLists which can
// collect component members in a single traversal, and IsConnected which
// is an even simpler boolean test.
func (g LabeledUndirected) ConnectedComponentReps() (reps []NI, orders, arcSizes []int) {
a := g.LabeledAdjacencyList
c := bits.New(len(a))
var o, ma int
var df func(NI)
df = func(n NI) {
c.SetBit(int(n), 1)
o++
ma += len(a[n])
for _, nb := range a[n] {
if c.Bit(int(nb.To)) == 0 {
df(nb.To)
}
}
return
}
for n := range a {
if c.Bit(n) == 0 {
o, ma = 0, 0
df(NI(n))
reps = append(reps, NI(n))
orders = append(orders, o)
arcSizes = append(arcSizes, ma)
}
}
return
}
// Copy makes a deep copy of g.
// Copy also computes the arc size ma, the number of arcs.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) Copy() (c LabeledUndirected, ma int) {
l, s := g.LabeledAdjacencyList.Copy()
return LabeledUndirected{l}, s
}
// Degeneracy is a measure of dense subgraphs within a graph.
//
// See Wikipedia https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)
//
// See also method DegeneracyOrdering which returns a degeneracy node
// ordering and k-core breaks.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) Degeneracy() (k int) {
a := g.LabeledAdjacencyList
// WP algorithm, attributed to Matula and Beck.
L := bits.New(len(a))
d := make([]int, len(a))
var D [][]NI
for v, nb := range a {
dv := len(nb)
d[v] = dv
for len(D) <= dv {
D = append(D, nil)
}
D[dv] = append(D[dv], NI(v))
}
for range a {
// find a non-empty D
i := 0
for len(D[i]) == 0 {
i++
}
// k is max(i, k)
if i > k {
k = i
}
// select from D[i]
Di := D[i]
last := len(Di) - 1
v := Di[last]
// Add v to ordering, remove from Di
L.SetBit(int(v), 1)
D[i] = Di[:last]
// move neighbors
for _, nb := range a[v] {
if L.Bit(int(nb.To)) == 1 {
continue
}
dn := d[nb.To] // old number of neighbors of nb
Ddn := D[dn] // nb is in this list
// remove it from the list
for wx, w := range Ddn {
if w == nb.To {
last := len(Ddn) - 1
Ddn[wx], Ddn[last] = Ddn[last], Ddn[wx]
D[dn] = Ddn[:last]
}
}
dn-- // new number of neighbors
d[nb.To] = dn
// re--add it to it's new list
D[dn] = append(D[dn], nb.To)
}
}
return
}
// DegeneracyOrdering computes degeneracy node ordering and k-core breaks.
//
// See Wikipedia https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)
//
// In return value ordering, nodes are ordered by their "coreness" as
// defined at https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)#k-Cores.
//
// Return value kbreaks indexes ordering by coreness number. len(kbreaks)
// will be one more than the graph degeneracy as returned by the Degeneracy
// method. If degeneracy is d, d = len(kbreaks) - 1, kbreaks[d] is the last
// value in kbreaks and ordering[:kbreaks[d]] contains nodes of the d-cores
// of the graph. kbreaks[0] is always the number of nodes in g as all nodes
// are in in a 0-core.
//
// Note that definitions of "k-core" differ on whether a k-core must be a
// single connected component. This method does not resolve individual
// connected components.
//
// See also method Degeneracy which returns just the degeneracy number.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) DegeneracyOrdering() (ordering []NI, kbreaks []int) {
a := g.LabeledAdjacencyList
// WP algorithm
k := 0
ordering = make([]NI, len(a))
kbreaks = []int{len(a)}
L := bits.New(len(a))
d := make([]int, len(a))
var D [][]NI
for v, nb := range a {
dv := len(nb)
d[v] = dv
for len(D) <= dv {
D = append(D, nil)
}
D[dv] = append(D[dv], NI(v))
}
for ox := len(a) - 1; ox >= 0; ox-- {
// find a non-empty D
i := 0
for len(D[i]) == 0 {
i++
}
// k is max(i, k)
if i > k {
for len(kbreaks) <= i {
kbreaks = append(kbreaks, ox+1)
}
k = i
}
// select from D[i]
Di := D[i]
last := len(Di) - 1
v := Di[last]
// Add v to ordering, remove from Di
ordering[ox] = v
L.SetBit(int(v), 1)
D[i] = Di[:last]
// move neighbors
for _, nb := range a[v] {
if L.Bit(int(nb.To)) == 1 {
continue
}
dn := d[nb.To] // old number of neighbors of nb
Ddn := D[dn] // nb is in this list
// remove it from the list
for wx, w := range Ddn {
if w == nb.To {
last := len(Ddn) - 1
Ddn[wx], Ddn[last] = Ddn[last], Ddn[wx]
D[dn] = Ddn[:last]
}
}
dn-- // new number of neighbors
d[nb.To] = dn
// re--add it to it's new list
D[dn] = append(D[dn], nb.To)
}
}
//for i, j := 0, k; i < j; i, j = i+1, j-1 {
// kbreaks[i], kbreaks[j] = kbreaks[j], kbreaks[i]
//}
return
}
// Degree for undirected graphs, returns the degree of a node.
//
// The degree of a node in an undirected graph is the number of incident
// edges, where loops count twice.
//
// If g is known to be loop-free, the result is simply equivalent to len(g[n]).
// See handshaking lemma example at AdjacencyList.ArcSize.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) Degree(n NI) int {
to := g.LabeledAdjacencyList[n]
d := len(to) // just "out" degree,
for _, to := range to {
if to.To == n {
d++ // except loops count twice
}
}
return d
}
// DegreeCentralization returns the degree centralization metric of a graph.
//
// Degree of a node is one measure of node centrality and is directly
// available from the adjacency list representation. This allows degree
// centralization for the graph to be very efficiently computed.
//
// The value returned is from 0 to 1 inclusive for simple graphs of three or
// more nodes. As a special case, 0 is returned for graphs of two or fewer
// nodes. The value returned can be > 1 for graphs with loops or parallel
// edges.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) DegreeCentralization() float64 {
a := g.LabeledAdjacencyList
if len(a) <= 2 {
return 0
}
var max, sum int
for _, to := range a {
if len(to) > max {
max = len(to)
}
sum += len(to)
}
return float64(len(a)*max-sum) / float64((len(a)-1)*(len(a)-2))
}
// Density returns density for a simple graph.
//
// See also Density function.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) Density() float64 {
return Density(g.Order(), g.Size())
}
// Eulerian scans an undirected graph to determine if it is Eulerian.
//
// If the graph represents an Eulerian cycle, it returns -1, -1, nil.
//
// If the graph does not represent an Eulerian cycle but does represent an
// Eulerian path, it returns the two end nodes of the path, and nil.
//
// Otherwise it returns an error.
//
// See also method EulerianStart, which short-circuits as soon as it finds
// a node that must be a start or end node of an Eulerian path.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) Eulerian() (end1, end2 NI, err error) {
end1 = -1
end2 = -1
for n := range g.LabeledAdjacencyList {
switch {
case g.Degree(NI(n))%2 == 0:
case end1 < 0:
end1 = NI(n)
case end2 < 0:
end2 = NI(n)
default:
err = errors.New("non-Eulerian")
return
}
}
return
}
// EulerianCycle finds an Eulerian cycle in an undirected multigraph.
//
// * If g has no nodes, result is nil, nil.
//
// * If g is Eulerian, result is an Eulerian cycle with err = nil.
// The first element of the result represents only a start node.
// The remaining elements represent the half arcs of the cycle.
//
// * Otherwise, result is nil, with a non-nil error giving a reason the graph
// is not Eulerian.
//
// Internally, EulerianCycle copies the entire graph g.
// See EulerianCycleD for a more space efficient version.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) EulerianCycle() ([]Half, error) {
c, _ := g.Copy()
return c.EulerianCycleD(c.Size())
}
// EulerianCycleD finds an Eulerian cycle in an undirected multigraph.
//
// EulerianCycleD is destructive on its receiver g. See EulerianCycle for
// a non-destructive version.
//
// Parameter m must be the size of the undirected graph -- the
// number of edges. Use Undirected.Size if the size is unknown.
//
// * If g has no nodes, result is nil, nil.
//
// * If g is Eulerian, result is an Eulerian cycle with err = nil.
// The first element of the result represents only a start node.
// The remaining elements represent the half arcs of the cycle.
//
// * Otherwise, result is nil, with a non-nil error giving a reason the graph
// is not Eulerian.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) EulerianCycleD(m int) ([]Half, error) {
if g.Order() == 0 {
return nil, nil
}
e := newLabEulerian(g.LabeledAdjacencyList, m)
e.p[0] = Half{0, -1}
for e.s >= 0 {
v := e.top()
if err := e.pushUndir(); err != nil {
return nil, err
}
if e.top().To != v.To {
return nil, errors.New("not Eulerian")
}
e.keep()
}
if !e.uv.AllZeros() {
return nil, errors.New("not strongly connected")
}
return e.p, nil
}
// EulerianPath finds an Eulerian path in an undirected multigraph.
//
// * If g has no nodes, result is nil, nil.
//
// * If g has an Eulerian path, result is an Eulerian path with err = nil.
// The first element of the result represents only a start node.
// The remaining elements represent the half arcs of the path.
//
// * Otherwise, result is nil, with a non-nil error giving a reason the graph
// is not Eulerian.
//
// Internally, EulerianPath copies the entire graph g.
// See EulerianPathD for a more space efficient version.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) EulerianPath() ([]Half, error) {
c, _ := g.Copy()
start := c.EulerianStart()
if start < 0 {
start = 0
}
return c.EulerianPathD(c.Size(), start)
}
// EulerianPathD finds an Eulerian path in a undirected multigraph.
//
// EulerianPathD is destructive on its receiver g. See EulerianPath for
// a non-destructive version.
//
// Argument m must be the correct size, or number of edges in g.
// Argument start must be a valid start node for the path.
//
// * If g has no nodes, result is nil, nil.
//
// * If g has an Eulerian path starting at start, result is an Eulerian path
// with err = nil.
// The first element of the result represents only a start node.
// The remaining elements represent the half arcs of the path.
//
// * Otherwise, result is nil, with a non-nil error giving a reason the graph
// is not Eulerian.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) EulerianPathD(m int, start NI) ([]Half, error) {
if g.Order() == 0 {
return nil, nil
}
e := newLabEulerian(g.LabeledAdjacencyList, m)
e.p[0] = Half{start, -1}
// unlike EulerianCycle, the first path doesn't have to be a cycle.
if err := e.pushUndir(); err != nil {
return nil, err
}
e.keep()
for e.s >= 0 {
start = e.top().To
e.push()
// paths after the first must be cycles though
// (as long as there are nodes on the stack)
if e.top().To != start {
return nil, errors.New("no Eulerian path")
}
e.keep()
}
if !e.uv.AllZeros() {
return nil, errors.New("no Eulerian path")
}
return e.p, nil
}
// EulerianStart finds a candidate start node for an Eulerian path.
//
// A graph representing an Eulerian path can have two nodes with odd degree.
// If it does, these must be the end nodes of the path. EulerianEnd scans
// for a node with an odd degree, returning immediately with the first one
// it finds.
//
// If the scan completes without finding a node with odd degree the method
// returns -1.
//
// See also method Eulerian, which completely validates a graph as representing
// an Eulerian path.
//
// There are equivalent labeled and unlabeled versions of this method.
func (g LabeledUndirected) EulerianStart() NI {
for n := range g.LabeledAdjacencyList {
if g.Degree(NI(n))%2 != 0 {
return NI(n)
}
}
return -1
}
// AddNode maps a node in a supergraph to a subgraph node.
//
// Argument p must be an NI in supergraph s.Super. AddNode panics if
// p is not a valid node index of s.Super.
//
// AddNode is idempotent in that it does not add a new node to the subgraph if
// a subgraph node already exists mapped to supergraph node p.
//
// The mapped subgraph NI is returned.
func (s *LabeledUndirectedSubgraph) AddNode(p NI) (b NI) {
if int(p) < 0 || int(p) >= s.Super.Order() {
panic(fmt.Sprint("AddNode: NI ", p, " not in supergraph"))
}
if b, ok := s.SubNI[p]; ok {
return b
}
a := s.LabeledUndirected.LabeledAdjacencyList
b = NI(len(a))
s.LabeledUndirected.LabeledAdjacencyList = append(a, nil)
s.SuperNI = append(s.SuperNI, p)
s.SubNI[p] = b
return
}
// InduceList constructs a node-induced subgraph.
//
// The subgraph is induced on receiver graph g. Argument l must be a list of
// NIs in receiver graph g. Receiver g becomes the supergraph of the induced
// subgraph.
//
// Duplicate NIs are allowed in list l. The duplicates are effectively removed
// and only a single corresponding node is created in the subgraph. Subgraph
// NIs are mapped in the order of list l, execpt for ignoring duplicates.
// NIs in l that are not in g will panic.
//
// Returned is the constructed Subgraph object containing the induced subgraph
// and the mappings to the supergraph.
func (g *LabeledUndirected) InduceList(l []NI) *LabeledUndirectedSubgraph {
sub, sup := mapList(l)
return &LabeledUndirectedSubgraph{
Super: g,
SubNI: sub,
SuperNI: sup,
LabeledUndirected: LabeledUndirected{
g.LabeledAdjacencyList.induceArcs(sub, sup),
}}
}
// InduceBits constructs a node-induced subgraph.
//