-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathattr.gi
More file actions
3472 lines (3140 loc) · 105 KB
/
attr.gi
File metadata and controls
3472 lines (3140 loc) · 105 KB
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
#############################################################################
##
## attr.gi
## Copyright (C) 2014-21 James D. Mitchell
##
## Licensing information can be found in the README file of this package.
##
#############################################################################
##
InstallMethod(DigraphNrVertices, "for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep], DIGRAPH_NR_VERTICES);
InstallGlobalFunction(OutNeighbors, OutNeighbours);
# The next method is (yet another) DFS which simultaneously computes:
# 1. *articulation points* as described in
# https://www.eecs.wsu.edu/~holder/courses/CptS223/spr08/slides/graphapps.pdf
# 2. *bridges* as described in https://stackoverflow.com/q/28917290/
# (this is a minor adaption of the algorithm described in point 1).
# 3. a *strong orientation* as alluded to somewhere on the internet that I can
# no longer find. It's essentially just "orient every edge in the DFS tree
# away from the root, and every other edge (back edges) from the node with
# higher `pre` value to the one with lower `pre` value (i.e. they point
# backwards from later nodes in the DFS to earlier ones). If the graph is
# bridgeless, then it is guaranteed that the orientation of the last
# sentence is strongly connected."
BindGlobal("DIGRAPHS_ArticulationPointsBridgesStrongOrientation",
function(D)
local N, copy, articulation_points, bridges, orientation, nbs, counter, pre,
low, nr_children, stack, u, v, i, w, connected;
N := DigraphNrVertices(D);
if HasIsConnectedDigraph(D) and not IsConnectedDigraph(D) then
# not connected, no articulation points, no bridges, no strong orientation
return [false, [], [], fail];
elif N < 2 then
# connected, no articulation points (removing 0 or 1 nodes does not make
# the graph disconnected), no bridges, strong orientation (since
# the digraph with 0 nodes is strongly connected).
return [true, [], [], D];
elif not IsSymmetricDigraph(D) then
copy := DigraphSymmetricClosure(DigraphMutableCopyIfMutable(D));
MakeImmutable(copy);
else
copy := D;
fi;
# outputs
articulation_points := [];
bridges := [];
orientation := List([1 .. N], x -> BlistList([1 .. N], []));
# Get out-neighbours once, to avoid repeated copying for mutable digraphs.
nbs := OutNeighbours(copy);
# number of nodes encountered in the search so far
counter := 0;
# the order in which the nodes are visited, -1 indicates "not yet visited".
pre := ListWithIdenticalEntries(N, -1);
# low[i] is the lowest value in pre currently reachable from node i.
low := [];
# nr_children of node 1, for articulation points the root node (1) is an
# articulation point if and only if it has at least 2 children.
nr_children := 0;
stack := Stack();
u := 1;
v := 1;
i := 0;
repeat
if pre[v] <> -1 then
# backtracking
i := Pop(stack);
v := Pop(stack);
u := Pop(stack);
w := nbs[v][i];
if v <> 1 and low[w] >= pre[v] then
Add(articulation_points, v);
fi;
if low[w] = pre[w] then
Add(bridges, [v, w]);
fi;
if low[w] < low[v] then
low[v] := low[w];
fi;
else
# diving - part 1
counter := counter + 1;
pre[v] := counter;
low[v] := counter;
fi;
i := PositionProperty(nbs[v], w -> w <> v, i);
while i <> fail do
w := nbs[v][i];
if pre[w] <> -1 then
# v -> w is a back edge
if w <> u and pre[w] < low[v] then
low[v] := pre[w];
fi;
orientation[v][w] := not orientation[w][v];
i := PositionProperty(nbs[v], w -> w <> v, i);
else
# diving - part 2
if v = 1 then
nr_children := nr_children + 1;
fi;
orientation[v][w] := true;
Push(stack, u);
Push(stack, v);
Push(stack, i);
u := v;
v := w;
i := 0;
break;
fi;
od;
until Size(stack) = 0;
if counter = DigraphNrVertices(D) then
connected := true;
if nr_children > 1 then
Add(articulation_points, 1);
fi;
if not IsEmpty(bridges) then
orientation := fail;
else
orientation := DigraphByAdjacencyMatrix(DigraphMutabilityFilter(D),
orientation);
fi;
else
connected := false;
articulation_points := [];
bridges := [];
orientation := fail;
fi;
if IsImmutableDigraph(D) then
SetIsConnectedDigraph(D, connected);
SetArticulationPoints(D, articulation_points);
SetBridges(D, bridges);
if IsSymmetricDigraph(D) then
SetStrongOrientationAttr(D, orientation);
fi;
fi;
return [connected, articulation_points, bridges, orientation];
end);
InstallMethod(ArticulationPoints, "for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep],
D -> DIGRAPHS_ArticulationPointsBridgesStrongOrientation(D)[2]);
InstallMethod(Bridges, "for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep],
D -> DIGRAPHS_ArticulationPointsBridgesStrongOrientation(D)[3]);
InstallMethodThatReturnsDigraph(StrongOrientation,
"for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep],
function(D)
if not IsSymmetricDigraph(D) then
ErrorNoReturn("not yet implemented");
fi;
return DIGRAPHS_ArticulationPointsBridgesStrongOrientation(D)[4];
end);
# Utility function to calculate the maximal independent sets (as BLists) of a
# subgraph induced by removing a set of vertices.
BindGlobal("DIGRAPHS_MaximalIndependentSetsSubtractedSet",
function(I, subtracted_set, size_bound)
local induced_mis, temp, i;
# First remove all vertices in the subtracted set from each MIS
temp := List(I, i -> DifferenceBlist(i, subtracted_set));
induced_mis := [];
# Then remove any sets which are no longer maximal
# Sort in decreasing size
Sort(temp, {x, y} -> SizeBlist(x) > SizeBlist(y));
# Then check elements from back to front for if they are a subset
for i in temp do
if SizeBlist(i) <= size_bound and
ForAll(induced_mis, x -> not IsSubsetBlist(x, i)) then
Add(induced_mis, i);
fi;
od;
return induced_mis;
end
);
InstallMethod(DIGRAPHS_AbsorbingMarkovChain,
"for a digraph",
[IsDigraph],
function(D)
# Helper for DigraphAbsorptionProbabilities and DigraphAbsorptionExpectedSteps
local scc, is_sink_comp, transient_vertices, i, comp, v, sink_comps,
nr_transients, transient_mat, absorption_mat, neighbours, chance, w,
w_comp, sink_comp_index, j, fundamental_mat;
scc := DigraphStronglyConnectedComponents(D);
# Find the "sink components" (components from which there is no escape)
# We could use QuotientDigraph and DigraphSinks here, but this avoids copying.
is_sink_comp := ListWithIdenticalEntries(Length(scc.comps), true);
transient_vertices := [];
for i in [1 .. Length(scc.comps)] do
comp := scc.comps[i];
for v in comp do
if ForAny(OutNeighboursOfVertex(D, v), w -> not w in comp) then
is_sink_comp[i] := false;
Append(transient_vertices, comp);
break;
fi;
od;
od;
sink_comps := Positions(is_sink_comp, true);
nr_transients := Length(transient_vertices);
# If no transient vertices, then we can't return anything interesting.
if nr_transients = 0 then
return rec(transient_vertices := transient_vertices,
fundamental_mat := [],
sink_comps := sink_comps,
absorption_mat := []);
fi;
# transient_mat[i][j] is the chance of going
# from transient vertex i to transient vertex j
transient_mat := NullMat(nr_transients, nr_transients);
# absorption_mat[i][j] is the chance of going
# from transient vertex i to sink component j
absorption_mat := NullMat(nr_transients, Length(sink_comps));
for i in [1 .. Length(transient_vertices)] do
v := transient_vertices[i];
neighbours := OutNeighboursOfVertex(D, v);
chance := 1 / Length(neighbours); # chance of following each edge
for w in neighbours do
w_comp := scc.id[w];
if is_sink_comp[w_comp] then
# w is in a sink component
sink_comp_index := Position(sink_comps, w_comp);
Assert(1, w in scc.comps[sink_comps[sink_comp_index]]);
absorption_mat[i][sink_comp_index] :=
absorption_mat[i][sink_comp_index] + chance;
else
# w is a transient vertex
j := Position(transient_vertices, w);
transient_mat[i][j] := transient_mat[i][j] + chance;
fi;
od;
od;
# "Fundamental matrix": mat[i][j] is the expected number of visits to each
# transient vertex j given a random walk starting at transient vertex i.
# Compute this using formula (I - Q)^-1
fundamental_mat := Inverse(IdentityMat(nr_transients) - transient_mat);
# Return all info needed for further computation in DigraphAbsorption* methods
return rec(transient_vertices := transient_vertices,
fundamental_mat := fundamental_mat,
sink_comps := sink_comps,
absorption_mat := absorption_mat);
end);
InstallMethod(DigraphAbsorptionProbabilities,
"for a digraph",
[IsDigraph],
function(D)
local scc, markov, chances_of_absorption, output, sink_comps, comp_no, v,
transient_vertices, i, j, c;
# Strongly connected components are an important part of definition
scc := DigraphStronglyConnectedComponents(D);
# One SCC only (or none): all vertices stay in it with probability 1.
if Length(scc.comps) <= 1 then
return ListWithIdenticalEntries(DigraphNrVertices(D), [1]);
fi;
# Get data about absorbing Markov chain represented by this digraph
markov := DIGRAPHS_AbsorbingMarkovChain(D);
# Calculate chances of absorption
# Rows are transient vertices, columns are absorbing SCCs
if Length(markov.transient_vertices) = 0 then
chances_of_absorption := [];
else
chances_of_absorption := markov.fundamental_mat * markov.absorption_mat;
fi;
# Convert to output format
# Rows are all vertices, columns are all SCCs
output := NullMat(DigraphNrVertices(D), Length(scc.comps));
# Non-transient vertices stay in their own SCC with probability 1
sink_comps := markov.sink_comps;
for comp_no in sink_comps do
for v in scc.comps[comp_no] do
output[v][comp_no] := 1;
od;
od;
# Transient vertices have chances as calculated in Markov code
transient_vertices := markov.transient_vertices;
for i in [1 .. Length(transient_vertices)] do
v := transient_vertices[i];
for j in [1 .. Length(sink_comps)] do
c := sink_comps[j];
output[v][c] := chances_of_absorption[i][j];
od;
od;
return output;
end);
InstallMethod(DigraphAbsorptionExpectedSteps,
"for a digraph",
[IsDigraph],
function(D)
local markov, N, transient_expected_steps, out, i;
if DigraphNrVertices(D) = 0 then
return [];
fi;
markov := DIGRAPHS_AbsorbingMarkovChain(D);
N := markov.fundamental_mat;
if Length(N) = 0 then # no transient vertices
transient_expected_steps := [];
else
transient_expected_steps := N * ListWithIdenticalEntries(Length(N), 1);
fi;
out := ListWithIdenticalEntries(DigraphNrVertices(D), 0);
for i in [1 .. Length(transient_expected_steps)] do
out[markov.transient_vertices[i]] := transient_expected_steps[i];
od;
return out;
end);
BindGlobal("DIGRAPHS_ChromaticNumberLawler",
function(D)
local n, vertices, subset_colours, s, S, i, I, subset_iter, x,
mis, subset_mis;
n := DigraphNrVertices(D);
vertices := List(DigraphVertices(D));
# Store all the Maximal Independent Sets, which can later be used for
# calculating the maximal independent sets of induced subgraphs.
mis := DigraphMaximalIndependentSets(D);
# Convert each MIS to a Blist
mis := List(mis, x -> BlistList(vertices, x));
# Store current best colouring for each subset
subset_colours := ListWithIdenticalEntries(2 ^ n, infinity);
# Empty set can be colouring with only one colour.
subset_colours[1] := 0;
# Iterator for blist subsets.
subset_iter := ListWithIdenticalEntries(n, [false, true]);
subset_iter := IteratorOfCartesianProduct2(subset_iter);
# Skip the first one, which should be the empty set.
S := NextIterator(subset_iter);
# Iterate over all vertex subsets.
for S in subset_iter do
# Cartesian iterator is ascending lexicographically, but we want reverse
# lexicographic ordering. We treat this as iterating over the complement.
# Index the current subset that is being iterated over.
s := 1;
for x in [1 .. n] do
# Need to negate, as we are iterating over the complement.
if not S[x] then
s := s + 2 ^ (x - 1);
fi;
od;
# Iterate over the maximal independent sets of V[S]
subset_mis :=
DIGRAPHS_MaximalIndependentSetsSubtractedSet(mis, S, infinity);
# Flip the list, as we now need the actual set.
FlipBlist(S);
for I in subset_mis do
# Calculate S \ I. This is destructive, but is undone.
SubtractBlist(S, I);
# Index S \ I
i := 1;
for x in [1 .. n] do
if S[x] then
i := i + 2 ^ (x - 1);
fi;
od;
# The chromatic number of this subset is the minimum value of all
# the maximal independent subsets of D[S].
subset_colours[s] := Minimum(subset_colours[s], subset_colours[i] + 1);
# Undo the changes to the subset.
UniteBlist(S, I);
od;
od;
return subset_colours[2 ^ n];
end
);
BindGlobal("DIGRAPHS_UnderThreeColourable",
function(D)
local nr;
nr := DigraphNrVertices(D);
if DigraphHasLoops(D) then
ErrorNoReturn("the argument <D> must be a digraph with no loops,");
elif nr = 0 then
return 0; # chromatic number = 0 iff <D> has 0 verts
elif IsNullDigraph(D) then
return 1; # chromatic number = 1 iff <D> has >= 1 verts & no edges
elif IsBipartiteDigraph(D) then
return 2; # chromatic number = 2 iff <D> has >= 2 verts & is bipartite
# <D> has at least 2 vertices at this stage
elif DigraphColouring(D, 3) <> fail then
# Check if there is a 3 colouring
return 3;
fi;
return infinity;
end
);
BindGlobal("DIGRAPHS_ChromaticNumberByskov",
function(D)
local n, a, vertices, subset_colours, S, i, j, I, subset_iter,
index_subsets, vertex_blist, k, MIS;
n := DigraphNrVertices(D);
vertices := DigraphVertices(D);
vertex_blist := BlistList(vertices, vertices);
# Store all the Maximal Independent Sets, which can later be used for
# calculating the maximal independent sets of induced subgraphs.
MIS := DigraphMaximalIndependentSets(D);
# Convert each MIS to a Blist
MIS := List(MIS, x -> BlistList(vertices, x));
# Store current best colouring for each subset
subset_colours := ListWithIdenticalEntries(2 ^ n, infinity);
# Empty set is 0 colourable
subset_colours[1] := 0;
# Function to index the subsets of the vertices of D
index_subsets := function(subset)
local x, index;
index := 1;
for x in [1 .. n] do
if subset[x] then
index := index + 2 ^ (x - 1);
fi;
od;
return index;
end;
# Iterate over vertex subsets
subset_iter := IteratorOfCombinations(vertices);
# Skip the first one, which should be the empty set
S := NextIterator(subset_iter);
Assert(1, IsEmpty(S), "First set from iterator should be the empty set");
# First find the 3 colourable subgraphs of D
for S in subset_iter do
a := DIGRAPHS_UnderThreeColourable(InducedSubdigraph(D, S));
S := BlistList(vertices, S);
i := index_subsets(S);
# Mark this as three or less colourable if it is.
subset_colours[i] := Minimum(a, subset_colours[i]);
od;
# Process 4 colourable subgraphs
for I in MIS do
SubtractBlist(vertex_blist, I);
# Iterate over all subsets of V(D) \ I as blists
# This is done by taking the cartesian product of n copies of [true, false]
# or [true] if the vertex is in I. The [true] is used as each element will
# be flipped to get reverse lexicographic ordering.
subset_iter := EmptyPlist(n);
for i in [1 .. n] do
if I[i] then
subset_iter[i] := [true];
else
subset_iter[i] := [true, false];
fi;
od;
subset_iter := IteratorOfCartesianProduct2(subset_iter);
# Skip the empty set.
NextIterator(subset_iter);
for S in subset_iter do
FlipBlist(S);
i := index_subsets(S);
if subset_colours[i] = 3 then
# Index union of S and I
j := index_subsets(UnionBlist(S, I));
subset_colours[j] := Minimum(subset_colours[j], 4);
fi;
od;
# Undo the changes made.
UniteBlist(vertex_blist, I);
od;
# Iterate over vertex subset blists.
subset_iter := ListWithIdenticalEntries(n, [true, false]);
subset_iter := IteratorOfCartesianProduct2(subset_iter);
# Skip the first one, which should be the empty set
S := NextIterator(subset_iter);
for S in subset_iter do
# Cartesian iteratator goes in lexicographic order, but we want reverse.
FlipBlist(S);
# Index the current subset that is being iterated over
i := index_subsets(S);
if 4 <= subset_colours[i] and subset_colours[i] < infinity then
k := SizeBlist(S) / subset_colours[i];
# Iterate over the maximal independent sets of D[V \ S]
for I in DIGRAPHS_MaximalIndependentSetsSubtractedSet(MIS, S, k) do
# Index S union I
j := index_subsets(UnionBlist(S, I));
subset_colours[j] := Minimum(subset_colours[j], subset_colours[i] + 1);
od;
fi;
od;
return subset_colours[2 ^ n];
end
);
BindGlobal("DIGRAPHS_ChromaticNumberZykov",
function(D)
local nr, ZykovReduce, chrom;
nr := DigraphNrVertices(D);
# Recursive function call
ZykovReduce := function(D)
local nr, D_contract, vertices, v, x, y, i, j, adjacent;
nr := DigraphNrVertices(D);
# Update upper bound if possible.
chrom := Minimum(nr, chrom);
# Leaf nodes are either complete graphs or cliques that have size equal to
# the current upper bound. The chromatic number is then the smallest clique
# found.
# Cliques finder arguments:
# digraph = D - The graph
# hook = fail - hook is not required
# user_param = [] - user_param is a list as hook is fail
# limit = 1 - We only need one clique
# include = exclude = [] - We check all vertices
# max = false - This clique need not be maximal
# size = chrom - We want a clique the size of our upper bound
# reps = true - As we only care about the existence of the clique,
# we can instead search for representatives which is more efficient.
if not IsCompleteDigraph(D) and IsEmpty(CliquesFinder(D, fail, [], 1, [],
[], false, chrom,
true)) then
# Sort vertices by degree, so that higher degree vertices are picked first
# Picking higher degree vertices will make it more likely a clique will
# form in one of the modified graphs, which will terminate the recursion.
vertices := DigraphWelshPowellOrder(D);
# Get the adjacency function
adjacent := DigraphAdjacencyFunction(D);
# Choose two non-adjacent vertices x, y
for i in [1 .. nr] do
x := vertices[i];
# Search for the first vertex not adjacent to all others
# This is guaranteed to exist as D is not the complete graph.
if OutDegreeOfVertex(D, x) < nr - 1 then
# Now search for a non-adjacent vertex, prioritising higher degree
# ones
for j in [i + 1 .. nr] do
y := vertices[j];
if not adjacent(x, y) then
break;
fi;
od;
break;
fi;
od;
Assert(1, x <> y, "x and y must be different");
# Colour the vertex contraction.
# A contraction of a graph effectively merges two non adjacent vertices
# into a single new vertex with the edges merged.
# We merge y into x, keeping x.
# We could potentially use quotient digraph here, but the increased
# generality might cause this to get slower.
D_contract := DigraphMutableCopy(D);
for v in vertices do
# Iterate over all vertices that are not x or y
if v = x or v = y then
continue;
fi;
# Add any edge that involves y, but not already x to avoid duplication.
if adjacent(v, y) and not adjacent(v, x) then
DigraphAddEdge(D_contract, x, v);
DigraphAddEdge(D_contract, v, x);
fi;
od;
DigraphRemoveVertex(D_contract, y);
ZykovReduce(D_contract);
# Colour the edge addition
# This just adds symmetric edges between x and y;
DigraphAddEdge(D, [x, y]);
DigraphAddEdge(D, [y, x]);
ZykovReduce(D);
# Undo changes to the graph
DigraphRemoveEdge(D, [x, y]);
DigraphRemoveEdge(D, [y, x]);
fi;
end;
# Algorithm requires an undirected graph without multiple edges.
D := DigraphMutableCopy(D);
D := DigraphRemoveAllMultipleEdges(D);
D := DigraphSymmetricClosure(D);
# Use greedy colouring as an upper bound
chrom := RankOfTransformation(DigraphGreedyColouring(D), nr);
ZykovReduce(D);
return chrom;
end
);
BindGlobal("DIGRAPHS_ChromaticNumberChristofides",
function(D)
local nr, I, n, T, b, unprocessed, i, v_without_t, j, u, min_occurrences,
cur_occurrences, chrom, colouring, stack, vertices;
nr := DigraphNrVertices(D);
vertices := List(DigraphVertices(D));
# Initialise the required variables.
# Calculate all maximal independent sets of D.
I := DigraphMaximalIndependentSets(D);
# Convert each MIS into a BList
I := List(I, i -> BlistList(vertices, i));
# Upper bound for chromatic number.
chrom := nr;
# Set of vertices of D not in the current subgraph at level n.
T := ListWithIdenticalEntries(nr, false);
# Current search level of the subgraph tree.
n := 0;
# The maximal independent sets of V \ T at level n.
b := [ListWithIdenticalEntries(nr, false)];
# Number of unprocessed MIS's of V \ T from level 1 to n
unprocessed := ListWithIdenticalEntries(nr, 0);
# Would be jth colour class of the chromatic colouring of G.
colouring := List([1 .. nr], i -> BlistList(vertices, [i]));
# Stores current unprocessed MIS's of V \ T at level 1 to level n
stack := [];
# Now perform the search.
repeat
# Step 2
if n < chrom then
# Step 3
# If V = T then we've reached a null subgraph
if SizeBlist(T) = nr then
chrom := n;
SubtractBlist(T, b[n + 1]);
for i in [1 .. chrom] do
colouring[i] := b[i];
# TODO set colouring attribute
od;
else
# Step 4
# Compute the maximal independent sets of V \ T
v_without_t := DIGRAPHS_MaximalIndependentSetsSubtractedSet(I, T,
infinity);
# Step 5
# Pick u in V \ T such that u is in the fewest maximal independent sets.
u := -1;
min_occurrences := infinity;
# Flip T to get V \ T
FlipBlist(T);
# Convert to list to iterate over the vertices.
for i in ListBlist(vertices, T) do
# Count how many times this vertex appears in a MIS
cur_occurrences := Number(v_without_t, j -> j[i]);
if cur_occurrences < min_occurrences then
min_occurrences := cur_occurrences;
u := i;
fi;
od;
# Revert changes to T
FlipBlist(T);
Assert(1, u <> -1, "Vertex must be picked");
# Remove maximal independent sets not containing u.
v_without_t := Filtered(v_without_t, x -> x[u]);
# Add these MISs to the stack
Append(stack, v_without_t);
# Search has moved one level deeper
n := n + 1;
unprocessed[n] := Length(v_without_t);
fi;
else
# if n >= g then T = T \ b[n]
# This exceeds the current best bound, so stop search.
SubtractBlist(T, b[n + 1]);
fi;
# Step 6
while n <> 0 do
# step 7
if unprocessed[n] = 0 then
n := n - 1;
SubtractBlist(T, b[n + 1]);
else
# Step 8
# take an element from the top of the stack
i := Remove(stack);
unprocessed[n] := unprocessed[n] - 1;
b[n + 1] := i;
UniteBlist(T, i);
break;
fi;
od;
until n = 0;
return chrom;
end
);
InstallMethod(ChromaticNumber, "for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep],
function(D)
local nr, comps, upper, chrom, tmp_comps, tmp_upper, n, comp, bound, clique,
c, i, greedy_bound, brooks_bound;
nr := DigraphNrVertices(D);
if DigraphHasLoops(D) then
ErrorNoReturn("the argument <D> must be a digraph with no loops,");
elif nr = 0 then
return 0; # chromatic number = 0 iff <D> has 0 verts
elif IsNullDigraph(D) then
return 1; # chromatic number = 1 iff <D> has >= 1 verts & no edges
elif IsBipartiteDigraph(D) then
return 2; # chromatic number = 2 iff <D> has >= 2 verts & is bipartite
# <D> has at least 2 vertices at this stage
fi;
# Value option for alternative dispatch
if ValueOption("lawler") <> fail then
return DIGRAPHS_ChromaticNumberLawler(D);
elif ValueOption("byskov") <> fail then
return DIGRAPHS_ChromaticNumberByskov(D);
elif ValueOption("zykov") <> fail then
return DIGRAPHS_ChromaticNumberZykov(D);
elif ValueOption("christofides") <> fail then
return DIGRAPHS_ChromaticNumberChristofides(D);
fi;
# The chromatic number of <D> is at least 3 and at most nr
D := DigraphMutableCopy(D);
D := DigraphRemoveAllMultipleEdges(D);
D := DigraphSymmetricClosure(D);
MakeImmutable(D);
if IsCompleteDigraph(D) then
# chromatic number = nr iff <D> has >= 2 verts & this cond.
return nr;
elif nr = 4 then
# if nr = 4, then 3 is only remaining possible chromatic number
return 3;
elif 2 * nr = DigraphNrEdges(D)
and IsRegularDigraph(D) and Length(OutNeighboursOfVertex(D, 1)) = 2 then
# <D> is an odd-length cycle graph
return 3;
fi;
# The chromatic number of <D> is at least 3 and at most nr - 1
# The variable <chrom> is the current best known lower bound for the
# chromatic number of <D>.
chrom := 3;
# Prepare a list of connected components of D whose chromatic number we
# do not yet know.
if IsConnectedDigraph(D) then
comps := [D];
greedy_bound := RankOfTransformation(DigraphGreedyColouring(D), nr);
brooks_bound := Maximum(OutDegrees(D)); # Brooks' theorem
upper := [Minimum(greedy_bound, brooks_bound)];
chrom := Maximum(CliqueNumber(D), chrom);
else
tmp_comps := [];
tmp_upper := [];
for comp in DigraphConnectedComponents(D).comps do
n := Length(comp);
if chrom < n then
# If chrom >= n, then we can colour the vertices of comp using any n of
# the required (at least) chrom colours, and we do not have to consider
# comp.
# Note that n > chrom >= 3 and so comp is not null, so no need to check
# for that.
comp := InducedSubdigraph(DigraphMutableCopy(D), comp);
if IsCompleteDigraph(comp) then
# Since n > chrom, this is an improved lower bound for the overall
# chromatic number.
chrom := n;
elif not IsBipartiteDigraph(comp) then
# If comp is bipartite, then its chromatic number is 2, and, since
# the chromatic number of D is >= 3, this component can be
# ignored.
greedy_bound := RankOfTransformation(DigraphGreedyColouring(comp),
DigraphNrVertices(comp));
# Don't need to take odd cycles into account for Brooks' theorem,
# since they are 3-colourable and the chromatic number of D is >= 3.
brooks_bound := Maximum(OutDegrees(comp));
bound := Minimum(greedy_bound, brooks_bound);
if bound > chrom then
# If bound <= chrom, then comp can be coloured by at most chrom
# colours, and so we can ignore comp.
clique := CliqueNumber(comp);
if clique = bound then
# The chromatic number of this component is known, and it can be
# ignored, and clique = bound > chrom, and so clique is an
# improved lower bound for the chromatic number of D.
chrom := clique;
else
Add(tmp_comps, comp);
Add(tmp_upper, bound);
if clique > chrom then
chrom := clique;
fi;
fi;
fi;
fi;
fi;
od;
# Remove the irrelevant components since we have a possibly improved value
# of chrom.
comps := [];
upper := [];
for i in [1 .. Length(tmp_comps)] do
if chrom < DigraphNrVertices(tmp_comps[i]) and chrom < tmp_upper[i] then
Add(comps, tmp_comps[i]);
Add(upper, tmp_upper[i]);
fi;
od;
# Sort by size, since smaller components are easier to colour
SortParallel(comps, upper, {x, y} -> Size(x) < Size(y));
fi;
for i in [1 .. Length(comps)] do
# <c> is the current best upper bound for the chromatic number of comps[i]
c := upper[i];
while c > chrom and DigraphColouring(comps[i], c - 1) <> fail do
c := c - 1;
od;
if c > chrom then
chrom := c;
fi;
od;
return chrom;
end);
#
# The following method is currently useless, as the OutNeighbours are computed
# and set whenever a digraph is created. It could be reinstated later if we
# decide to allow digraphs to exist without known OutNeighbours.
#
# InstallMethod(OutNeighbours,
# "for a digraph with representative out neighbours and group",
# [IsDigraph and HasRepresentativeOutNeighbours and HasDigraphGroup],
# function(D)
# local gens, sch, reps, out, trace, word, i, w;
#
# gens := GeneratorsOfGroup(DigraphGroup(D));
# sch := DigraphSchreierVector(D);
# reps := RepresentativeOutNeighbours(D);
#
# out := EmptyPlist(DigraphNrVertices(D));
#
# for i in [1 .. Length(sch)] do
# if sch[i] < 0 then
# out[i] := reps[-sch[i]];
# fi;
#
# trace := DIGRAPHS_TraceSchreierVector(gens, sch, i);
# out[i] := out[trace.representative];
# word := trace.word;
# for w in word do
# out[i] := OnTuples(out[i], gens[w]);
# od;
# od;
# return out;
# end);
InstallMethod(DigraphAdjacencyFunction, "for a digraph by out-neighbours",
[IsDigraph], D -> {u, v} -> IsDigraphEdge(D, u, v));
InstallMethod(AsTransformation, "for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep],
function(D)
if not IsFunctionalDigraph(D) then
return fail;
fi;
return Transformation(Concatenation(OutNeighbours(D)));
end);
InstallMethod(DigraphNrEdges, "for a digraph", [IsDigraphByOutNeighboursRep],
function(D)
local m;
m := DIGRAPH_NREDGES(D);
if IsImmutableDigraph(D) then
SetIsEmptyDigraph(D, m = 0);
fi;
return m;
end);
InstallMethod(DigraphNrAdjacencies, "for a digraph",
[IsDigraphByOutNeighboursRep], DIGRAPH_NRADJACENCIES);
InstallMethod(DigraphNrAdjacenciesWithoutLoops, "for a digraph",
[IsDigraphByOutNeighboursRep], DIGRAPH_NRADJACENCIESWITHOUTLOOPS);
InstallMethod(DigraphNrLoops,
"for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep],
function(D)
local i, j, sum;
sum := 0;
if HasDigraphHasLoops(D) and not DigraphHasLoops(D) then
return 0;
else
for i in DigraphVertices(D) do
for j in OutNeighbours(D)[i] do
if i = j then
sum := sum + 1;
fi;
od;
od;
fi;
if IsImmutableDigraph(D) then
SetDigraphHasLoops(D, sum <> 0);
fi;
return sum;
end);
InstallMethod(DigraphNrLoops,
"for a digraph that knows its adjacency matrix",
[IsDigraphByOutNeighboursRep and HasAdjacencyMatrix],
function(D)
local A, i;
A := AdjacencyMatrix(D);
return Sum(DigraphVertices(D), i -> A[i][i]);
end);
InstallMethod(DigraphEdges, "for a digraph by out-neighbours",
[IsDigraphByOutNeighboursRep],
function(D)
local out, adj, nr, i, j;
out := EmptyPlist(DigraphNrEdges(D));
adj := OutNeighbours(D);
nr := 0;
for i in DigraphVertices(D) do
for j in adj[i] do
nr := nr + 1;
out[nr] := [i, j];
od;
od;
return out;
end);
# Hash related attributes
InstallMethod(DigraphHash, "for a digraph", [IsDigraph], DIGRAPH_HASH);
# To make built in Orbit function use DigraphHash
InstallMethod(SparseIntKey, "for an object and digraph",
[IsObject, IsDigraph],
{coll, D} -> DigraphHash
);
# To make orb package use DigraphHash
InstallMethod(ChooseHashFunction, "for a digraph and positive integer",
[IsDigraph, IsInt],
# TODO: (reiniscirpons) remove the rank when new semigroups version gets
# released.
2,
{D, hashlen} -> rec(func := {x, data} -> 1 + (DigraphHash(x) mod data[1]),
data := [hashlen])
);
# attributes for digraphs . . .
InstallMethod(AsGraph, "for a digraph", [IsDigraph], Graph);
InstallMethod(DigraphVertices, "for a digraph", [IsDigraph],
D -> [1 .. DigraphNrVertices(D)]);
InstallMethod(DigraphRange,
"for an immutable digraph by out-neighbours",
[IsDigraphByOutNeighboursRep and IsImmutableDigraph],
function(D)
if not IsBound(D!.DigraphRange) then
DIGRAPH_SOURCE_RANGE(D);
SetDigraphSource(D, D!.DigraphSource);
fi;
return D!.DigraphRange;
end);
InstallMethod(DigraphRange,
"for a mutable digraph by out-neighbours",
[IsDigraphByOutNeighboursRep and IsMutableDigraph],
D -> DIGRAPH_SOURCE_RANGE(D).DigraphRange);
InstallMethod(DigraphSource,
"for an immutable digraph by out-neighbours",
[IsDigraphByOutNeighboursRep and IsImmutableDigraph],
function(D)
if not IsBound(D!.DigraphSource) then
DIGRAPH_SOURCE_RANGE(D);