Ejemplo n.º 1
0
        public static List <Graphs.Vector> GetSpringsLayout(this Choosability.Graph g, int randomSeed)
        {
            var satsumaGraph = g.CreateSatsumaGraph();
            var layout       = new ForceDirectedLayout(satsumaGraph, null, randomSeed);

            layout.Run();

            var minX = double.MaxValue;
            var minY = double.MaxValue;
            var maxX = double.MinValue;
            var maxY = double.MinValue;

            foreach (var p in layout.NodePositions)
            {
                minX = Math.Min(minX, p.Value.X);
                minY = Math.Min(minY, p.Value.Y);
                maxX = Math.Max(maxX, p.Value.X);
                maxY = Math.Max(maxY, p.Value.Y);
            }

            var width  = maxX - minX;
            var height = maxY - minY;

            return(satsumaGraph.Nodes().Select(n => new Graphs.Vector(0.1 + 0.7 * (layout.NodePositions[n].X - minX) / width, 0.1 + 0.7 * (layout.NodePositions[n].Y - minY) / height)).ToList());
        }
Ejemplo n.º 2
0
        public static void WriteProof()
        {
            //  var uiG = GraphsCore.CompactSerializer.Deserialize("webgraph:7qM`$!.4bH!!!R&a9[/.`!KrS!Aa_K%n$+I!*C1-pbPd:TFX<n1&s-S7JJ\\_\"eHt>8?!.J7JQ4#6hiD:#64`)!<=YO!!!'6/-5ne/-I40\"U#Ji#\"0\"-!!!\"L\"p\"]T!<<"); //small tree aka fig1 left
            //     var uiG = GraphsCore.CompactSerializer.Deserialize("webgraph:7oB<e!-S>B!!#8TJd$*0\\-lgI!AXY2';,k%#;Z?^)[2gP(C-Of'0ujY!!N?&!.ZPL!<E0O!=+(&I\"$HlIKBKg/-?eA!uhdS2\\:FcIXV"); // fig1 middle

            //   var uiG = GraphsCore.CompactSerializer.Deserialize("webgraph:7qDZ#!2KSp!!#7s_?WaT\\-lgI!Aa^d)5%L-#>?-AShqSoSn&^p'0ujY!)+Du>Qb&\"e2/>6>R(6/!<E0O!=+(&I\"$HlIK0Hg/-6b%!s0Al\"<.mU.hDa^!.Y84&:T\"UIK"); // fig1 right

            //  var uiG = GraphsCore.CompactSerializer.Deserialize("webgraph:8!X,T!$D:B!!&)lOptM4\\-lgI!Aa^@+,/T#,DG#?+.s-1#;Q9])[2f],6a[K$V?KmJ;)mR%u&ns'8>>R$O*,X'*Xu#%gAPD(XNCQ#;Z>g!!*'#!6>-?Uf-F^IXZZnI\"$MF!ZK,^!?0#^$P3Il&-`@Xa9[/)$6$tl\"rbPjHP\"$p#ljsUL^OUs(<CrPIXV"); // big tree

            var uiG = GraphsCore.CompactSerializer.Deserialize("webgraph:7RI.U!'1)[!!@T`X:8\\?!AXXc)8lhl!!+kU9HC2DA,lWc!!3-$!!*'N!=+(&I\"$HlIK9KN!%\\-UIXZZnI\"$M"); // val

            var potSize  = uiG.Vertices.Max(v => int.Parse(v.Label));
            var g        = new Choosability.Graph(uiG.GetEdgeWeights());
            var template = new Template(g.Vertices.Select(v => potSize + g.Degree(v) - uiG.Vertices[v].Label.TryParseInt().Value).ToList());

            var mind = new Choosability.FixerBreaker.KnowledgeEngine.Slim.Super.SuperSlimMind(g, proofFindingMode: true);

            mind.MaxPot = potSize;
            //   mind.MissingEdgeIndex = 0;
            //   mind.OnlyConsiderNearlyColorableBoards = true;

            int j   = 0;
            var win = mind.Analyze(template);

            if (win)
            {
                var pb    = new MaximumDegreeThreeProofBuilder(mind);
                var proof = pb.WriteProof();
            }
        }
Ejemplo n.º 3
0
        AlgorithmBlob(TabCanvas tabCanvas)
        {
            UIGraph          = tabCanvas.GraphCanvas.Graph;
            AlgorithmGraph   = new Choosability.Graph(UIGraph.GetEdgeWeights());
            BitGraph         = new BitLevelGeneration.BitGraph_long(UIGraph.GetEdgeWeights());
            SelectedVertices = UIGraph.Vertices.Select((v, i) => v.IsSelected ? i : -1).Where(x => x >= 0).ToList();
            SelectedEdges    = UIGraph.Edges.Where(e => e.IsSelected).Select(e => new Tuple <int, int>(UIGraph.Vertices.IndexOf(e.V1), UIGraph.Vertices.IndexOf(e.V2))).ToList();

            EdgeIndexLookup = new Dictionary <Tuple <int, int>, int>();
            int k = 0;

            for (int i = 0; i < AlgorithmGraph.N; i++)
            {
                for (int j = i + 1; j < AlgorithmGraph.N; j++)
                {
                    if (AlgorithmGraph[i, j])
                    {
                        EdgeIndexLookup[new Tuple <int, int>(i, j)] = k;
                        EdgeIndexLookup[new Tuple <int, int>(j, i)] = k;
                        k++;
                    }
                }
            }

            SelectedEdgeIndices = SelectedEdges.Select(tuple => EdgeIndexLookup[tuple]).ToList();
        }
Ejemplo n.º 4
0
        static void DoEdgeAlls(Graphs.Graph uiG, int potSize, Choosability.Graph G, Template template, int i)
        {
            var mind = new Choosability.FixerBreaker.KnowledgeEngine.Slim.Super.SuperSlimMind(G);

            mind.MaxPot = potSize;
            mind.OnlyConsiderNearlyColorableBoards = true;
            mind.MissingEdgeIndex = i;

            var root = @"C:\game trees\alls2\" + i;

            Directory.CreateDirectory(root);

            var win = mind.Analyze(template, null);

            if (win)
            {
                int j = 0;
                foreach (var board in mind.PlayableBoards)
                {
                    var tree = mind.BuildGameTree(board);
                    GraphViz.DrawTree(tree, root + @"\" + i + " depth " + tree.GetDepth() + " board " + j + ".pdf");
                    j++;
                }
            }
        }
Ejemplo n.º 5
0
        void TestGraph <T>(string name, int totalPositions, bool shouldWin, bool shouldWinNearlyColorable)
            where T : IMind
        {
            var graphFile = Path.Combine(RootPath, name);

            Assert.IsTrue(File.Exists(graphFile), graphFile + " does not exist.");

            var graph = GraphUtility.LoadGraph(graphFile);
            var G     = new Choosability.Graph(graph.GetEdgeWeights());

            var potSize  = graph.Vertices.Max(v => v.Label.TryParseInt().Value);
            var template = new Template(G.Vertices.Select(v => potSize + G.Degree(v) - graph.Vertices[v].Label.TryParseInt().Value).ToList());

            var mind = (SuperSlimMind)Activator.CreateInstance(typeof(T), G);

            mind.MaxPot = potSize;

            var win = mind.Analyze(template, null);

            Assert.AreEqual(totalPositions, mind.TotalBoards, "total positions fail");
            Assert.AreEqual(shouldWin, win, "outright win fail");

            if (!win)
            {
                mind        = (SuperSlimMind)Activator.CreateInstance(typeof(T), G);
                mind.MaxPot = potSize;
                mind.OnlyConsiderNearlyColorableBoards = true;

                win = mind.Analyze(template, null);
                Assert.AreEqual(shouldWinNearlyColorable, win, "nearly colorable fail");
            }
        }
Ejemplo n.º 6
0
        static IEnumerable <Choosability.Graph> EnumerateWeightings(Choosability.Graph g)
        {
            var space = Not ? g.Vertices.Select(v => Enumerable.Range(0, Spread)).CartesianProduct() : g.Vertices.Select(v => Enumerable.Range(0, Spread).Reverse()).CartesianProduct();

            foreach (var weighting in space)
            {
                var www = weighting.ToList();
                if (www.Count(w => w > 0) > MaxHighs)
                {
                    continue;
                }

                if (g.Vertices.Any(v => g.Degree(v) - www[v] <= 1))
                {
                    continue;
                }

                if (LowMinDegree > 0)
                {
                    var low = www.IndicesWhere(w => w == 0).ToList();
                    if (g.InducedSubgraph(low).MinDegree < LowMinDegree)
                    {
                        continue;
                    }
                }

                var gg = g.Clone();
                gg.VertexWeight = www;

                yield return(gg);
            }
        }
Ejemplo n.º 7
0
        public static Supergraph CreateSatsumaGraph(this Choosability.Graph g)
        {
            var satsumaGraph = new CustomGraph();

            var nodes = new Dictionary <int, Node>();

            foreach (var v in g.Vertices)
            {
                var node = satsumaGraph.AddNode();
                nodes[v] = node;
            }

            for (int i = 0; i < g.N; i++)
            {
                for (int j = i + 1; j < g.N; j++)
                {
                    if (g.Directed[i, j])
                    {
                        satsumaGraph.AddArc(nodes[i], nodes[j], Directedness.Directed);
                    }
                    else if (g.Directed[j, i])
                    {
                        satsumaGraph.AddArc(nodes[j], nodes[i], Directedness.Directed);
                    }
                    else if (g.Adjacent[i, j])
                    {
                        satsumaGraph.AddArc(nodes[i], nodes[j], Directedness.Undirected);
                    }
                }
            }

            return(satsumaGraph);
        }
Ejemplo n.º 8
0
        static bool Filter(Choosability.Graph g)
        {
            if (TwoConnectedOnly)
            {
                return(g.Vertices.All(v => g.FindComponents(g.Vertices.Except(new[] { v }).ToList()).GetEquivalenceClasses().Count() <= 1));
            }

            return(true);
        }
Ejemplo n.º 9
0
        public static Graphs.Graph GraphFromGraph6(string graph6)
        {
            var w = GetEdgeWeights(graph6);
            var h = new Choosability.Graph(w);

            var g = new Graphs.Graph(h, h.GetSpringsLayout(12), false);

            g.Name = graph6;
            return(g);
        }
Ejemplo n.º 10
0
        public static string ToWeightString(this Choosability.Graph g)
        {
            var edgeWeights   = string.Join(" ", g.GetEdgeWeights().Select(x => x.ToString()));
            var vertexWeights = "";

            if (g.VertexWeight != null)
            {
                vertexWeights = " [" + string.Join(",", g.VertexWeight) + "]";
            }

            return(edgeWeights + vertexWeights);
        }
Ejemplo n.º 11
0
        public static List <Graphs.Vector> GetLaplacianLayout(this Choosability.Graph g, List <Graphs.Vector> layout = null, object data = null)
        {
            var D = Matrix.Build.Diagonal(g.N, g.N, v => g.Degree(v));
            var A = Matrix.Build.Dense(g.N, g.N, (v, w) => g[v, w] ? 1 : 0);
            var L = D - A;

            var evd = L.Evd(MathNet.Numerics.LinearAlgebra.Symmetricity.Symmetric);
            var x   = evd.EigenVectors.Column(1);
            var y   = evd.EigenVectors.Column(2);

            return(GetEigenVectorLayout(x, y));
        }
Ejemplo n.º 12
0
        static IEnumerable <Choosability.Graph> EnumerateWeightings(Choosability.Graph g)
        {
            if (g.MaxDegree > 4)
            {
                yield break;
            }

            foreach (var weighting in g.Vertices.Select(v => Enumerable.Range(g.Degree(v), 2)).CartesianProduct())
            {
                var www = weighting.ToList();

                var gg = g.Clone();
                gg.VertexWeight = www;
                yield return(gg);
            }
        }
Ejemplo n.º 13
0
        public static void DoUiGraph()
        {
            var output = "generated.txt";

            File.Delete(output);

            Graphs.Graph uiG;
            using (var sr = new StreamReader("uigraph.txt"))
                uiG = GraphsCore.CompactSerializer.Deserialize(sr.ReadToEnd());

            var excluded = "excluded.txt".EnumerateWeightedGraphs().ToList();

            var g = new Choosability.Graph(uiG.GetEdgeWeights(), uiG.Vertices.Select(v =>
            {
                int d;
                if (!int.TryParse(v.Label, out d))
                {
                    return(0);
                }

                return(d - 5);
            }).ToList());

            var all = new List <Graph>();

            var zi = g.VertexWeight.IndicesWhere(w => w == 0).ToList();

            foreach (var a in zi.Select(i => new[] { 1, 2 }).CartesianProduct())
            {
                var aa = a.ToList();
                for (int j = 0; j < aa.Count; j++)
                {
                    g.VertexWeight[zi[j]] = aa[j];
                }

                all.Add(g.Clone());
            }

            foreach (var gg in all.RemoveIsomorphs(excluded))
            {
                gg.AppendWeightStringToFile(output);
            }
        }
Ejemplo n.º 14
0
        public static Graphs.Graph GraphFromEdgeWeightString(string s)
        {
            var isDirected = s.Contains("-1");

            var parts       = s.Split(' ');
            var edgeWeights = parts.Where(p => !p.StartsWith("[")).Select(x => int.Parse(x)).ToList();

            List <int> vertexWeights = null;
            var        vwp           = parts.FirstOrDefault(p => p.StartsWith("["));

            if (vwp != null)
            {
                vertexWeights = vwp.Trim('[').Trim(']').Split(',').Select(x => int.Parse(x)).ToList();
            }

            var h = new Choosability.Graph(edgeWeights, vertexWeights);

            return(new Graphs.Graph(h, h.GetSpringsLayout(12), isDirected));
        }
Ejemplo n.º 15
0
        public static void BuildTreePictures()
        {
            var root = @"C:\game trees\smalltree\fixable";

            Directory.CreateDirectory(root);

            //   var uiG = GraphsCore.CompactSerializer.Deserialize("webgraph:7p5lm!.4bH!!#8TV?g9C\\-lgI!AXXW)k[^-#;Z?F*sJ5a,6aYM-O65sh^B_'h`q79;LfjChZj,^!!*)@!!!'$'Z^@ja9NC\"!sTF[\">gYm\"T\\VE!!!");
            //  var uiG = GraphsCore.CompactSerializer.Deserialize("webgraph:7s+e3!3?/#!!#:+U^KF0PS%F+!AXX?+05o;#;\\Xf`!Jd9-mM7W`P)m27JKt(6hiE-#!f!b-mM`?paS`-&1>N4<IG2S!<<-#a8c2A!>NTW'Z^Ila9)SZa98IB!.Zm;#6Y^]#ZM?A<\"KBC!<C1@!!");
            var uiG      = GraphsCore.CompactSerializer.Deserialize("webgraph:7qM`$!.4bH!!!R&a9[/.`!KrS!Aa_K%n$+I!*C1-pbPd:TFX<n1&s-S7JJ\\_\"eHt>8?!.J7JQ4#6hiD:#64`)!<=YO!!!'6/-5ne/-I40\"U#Ji#\"0\"-!!!\"L\"p\"]T!<<");
            var potSize  = uiG.Vertices.Max(v => int.Parse(v.Label));
            var g        = new Choosability.Graph(uiG.GetEdgeWeights());
            var template = new Template(g.Vertices.Select(v => potSize + g.Degree(v) - uiG.Vertices[v].Label.TryParseInt().Value).ToList());

            GraphViz.DrawGraph(g, root + @"\G.pdf", true);

            var mind = new Choosability.FixerBreaker.KnowledgeEngine.Slim.Super.SuperSlimMind(g, proofFindingMode: true);

            mind.MaxPot = potSize;
            //  mind.OnlyConsiderNearlyColorableBoards = true;
            //  mind.MissingEdgeIndex = 0;

            int j   = 0;
            var win = mind.Analyze(template);

            if (win)
            {
                foreach (var board in mind.PlayableBoards)
                {
                    var tree = mind.BuildGameTree(board, win);
                    GraphViz.DrawTree(tree, root + @"\" + " depth " + tree.GetDepth() + " board " + j + ".png");
                    j++;
                }
            }
            else
            {
                foreach (var board in mind.BreakerWonBoards)
                {
                    var tree = mind.BuildGameTree(board, win);
                    GraphViz.DrawTree(tree, root + @"\" + " depth " + tree.GetDepth() + " board " + j + ".png");
                    j++;
                }
            }
        }
Ejemplo n.º 16
0
        public static List <Graphs.Vector> GetWalkMatrixLayout(this Choosability.Graph g, List <Graphs.Vector> layout = null, object data = null)
        {
            var D = Matrix.Build.Diagonal(g.N, g.N, v => g.Degree(v));
            var A = Matrix.Build.Dense(g.N, g.N, (v, w) => g[v, w] ? 1 : 0);
            var L = D.Inverse() * A;

            var evd = L.Evd(MathNet.Numerics.LinearAlgebra.Symmetricity.Symmetric);
            int xi  = 1;
            int yi  = 2;

            for (int i = 0; i < evd.EigenValues.Count - 1; i++)
            {
                if (evd.EigenValues[i].Real <= 1 && evd.EigenValues[i + 1].Real >= 1)
                {
                    xi = i;
                    yi = i + 1;
                    break;
                }
            }
            var x = evd.EigenVectors.Column(xi);
            var y = evd.EigenVectors.Column(yi);

            return(GetEigenVectorLayout(x, y));
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            var vertices = Enumerable.Range(1, N).Select(i => new Fraction()
            {
                Top = (int)f((uint)i), Bottom = (int)f((uint)i + 1)
            }).ToList();
            // var vertices = new FareySequence(N).ToList();
            var adjacent = new bool[vertices.Count, vertices.Count];

            for (int i = 0; i < vertices.Count; i++)
            {
                for (int j = 0; j < vertices.Count; j++)
                {
                    adjacent[i, j] = adjacent[j, i] = Math.Abs(vertices[i].Top * vertices[j].Bottom - vertices[i].Bottom * vertices[j].Top) == 1.0;
                }
            }

            //var g = new Choosability.Graph(adjacent);
            //var R = g.Vertices;
            //var G = g.Vertices.Except(g.Vertices).ToList();
            List <int> R = null;
            List <int> G = null;
            var        g = new Choosability.Graph(adjacent);

            foreach (var red in g.EnumerateMaximalIndependentSets())
            {
                var bluegreen = g.Vertices.Except(red).ToList();
                var h         = g.InducedSubgraph(bluegreen);
                if (!h.IsTwoColorableSlow())
                {
                    continue;
                }
                R = red;
                foreach (var green in g.EnumerateMaximalIndependentSets(bluegreen))
                {
                    if (g.EdgesOn(bluegreen.Except(green).ToList()) <= 0)
                    {
                        G = green;
                        break;
                    }
                }

                if (G != null)
                {
                    break;
                }
            }

            var B = g.Vertices.Except(R).Except(G).ToList();

            using (var sw = new StreamWriter("Ford" + N + ".tex"))
            {
                sw.WriteLine(@"\documentclass{standalone}");
                sw.WriteLine(@"\usepackage{tikz}");
                sw.WriteLine(@"\begin{document}");
                sw.WriteLine(@"\begin{tikzpicture}");
                var circles = string.Join(Environment.NewLine, Enumerable.Range(1, N).Select(i => new Fraction()
                {
                    Top = (int)f((uint)i), Bottom = (int)f((uint)i + 1)
                }).Select(f => new FordCircle(f)).Select((f, i) => string.Format(@"\fill[{3}] ({0},{1}) circle [radius={2}];", f.X, f.Y, f.R, Fill(f.F, i, R, G))));
                sw.WriteLine(circles);
                sw.WriteLine(@"\end{tikzpicture}");
                sw.WriteLine(@"\end{document}");



                //var k = g.CliqueNumberBronKerbosch();
                //var gg = GraphIO.GraphFromEdgeWeightString(string.Join(" ", g.GetEdgeWeights()));
                //var s = CompactSerializer.Serialize(gg);
            }
        }
Ejemplo n.º 18
0
        public static List <Vector> RotateDiamondsLayout(Choosability.Graph g, List <Vector> layout = null, object data = null)
        {
            var dd = data as Tuple <List <Vector>, List <SpindleAnalyzer.DiamondType> >;

            return(layout.Select((v, i) => Rotate(dd.Item1[i], v, !(dd.Item2[i] == DiamondType.U || dd.Item2[i] == DiamondType.DR || dd.Item2[i] == DiamondType.DL))).ToList());
        }
Ejemplo n.º 19
0
 public static List <Graphs.Vector> GetSpringsLayout(this Choosability.Graph g, List <Graphs.Vector> layout = null, object data = null)
 {
     return(GetSpringsLayout(g, 0));
 }
Ejemplo n.º 20
0
 public static void AppendGraph6ToFile(this Choosability.Graph g, string path)
 {
     using (var sw = new StreamWriter(path, append: true))
         sw.WriteLine(g.ToGraph6());
 }
Ejemplo n.º 21
0
        public static List <Graphs.Vector> GetUnitDistanceLayout(this Choosability.Graph g, List <Graphs.Vector> layout = null, object data = null)
        {
            var modifiedLayout = layout.ToList();

            var maxDegree = g.MaxDegree;

            for (int qqq = 0; qqq < 10; qqq++)
            {
                var maxes = g.Vertices.ToList();
                maxes.Shuffle();

                foreach (var first in maxes)
                {
                    var nonzeroCount = 0;
                    var total        = 0.0;
                    for (int i = 0; i < g.N; i++)
                    {
                        for (int j = i + 1; j < g.N; j++)
                        {
                            if (g[i, j])
                            {
                                var d = modifiedLayout[i].Distance(modifiedLayout[j]);
                                if (d > 0)
                                {
                                    nonzeroCount++;
                                    total += d;
                                }
                            }
                        }
                    }

                    var length = total / Math.Max(1, nonzeroCount);

                    for (int qq = 0; qq < 10; qq++)
                    {
                        modifiedLayout = modifiedLayout.ToList();
                        var remaining = g.Vertices.Where(v => v != first).ToList();
                        remaining.Shuffle();
                        var anchor = new List <Tuple <int, Graphs.Vector> >()
                        {
                            new Tuple <int, Graphs.Vector>(first, modifiedLayout[first])
                        };

                        while (remaining.Count > 0)
                        {
                            var count   = remaining.Count;
                            var removed = new List <int>();
                            foreach (var v in remaining)
                            {
                                var neighbors = anchor.Where(a => g[a.Item1, v]).ToList();
                                if (neighbors.Count <= 0)
                                {
                                    continue;
                                }

                                if (neighbors.Count >= 2)
                                {
                                    var a = neighbors.First().Item2;
                                    var b = neighbors.Skip(1).First().Item2;

                                    double x1, y1, x2, y2;
                                    if (IntersectionOfTwoCircles(a.X, a.Y, length, b.X, b.Y, length, out x1, out y1, out x2, out y2))
                                    {
                                        var d1 = new Graphs.Vector(x1, y1).Distance(modifiedLayout[v]);
                                        var d2 = new Graphs.Vector(x2, y2).Distance(modifiedLayout[v]);

                                        if (d1 < d2 && d1 > 0.001)
                                        {
                                            modifiedLayout[v] = new Graphs.Vector(x1, y1);
                                        }
                                        else if (d2 < d1 && d2 > 0.001)
                                        {
                                            modifiedLayout[v] = new Graphs.Vector(x2, y2);
                                        }

                                        removed.Add(v);
                                        anchor.Add(new Tuple <int, Graphs.Vector>(v, modifiedLayout[v]));
                                    }
                                }
                            }

                            var tt = remaining.RemoveAll(v => removed.Contains(v));
                            removed.Clear();

                            if (tt == 0)
                            {
                                foreach (var v in remaining)
                                {
                                    var neighbors = anchor.Where(a => g[a.Item1, v]).ToList();
                                    if (neighbors.Count <= 0)
                                    {
                                        continue;
                                    }

                                    var p = neighbors.First().Item2;
                                    var q = modifiedLayout[v];

                                    var offset = q - p;
                                    var ok     = offset.Normalize();

                                    if (ok)
                                    {
                                        offset           *= length;
                                        modifiedLayout[v] = p + offset;

                                        removed.Add(v);
                                        anchor.Add(new Tuple <int, Graphs.Vector>(v, modifiedLayout[v]));
                                        goto skipper;
                                    }
                                }

skipper:
                                remaining.RemoveAll(v => removed.Contains(v));
                                if (remaining.Count == count)
                                {
                                    var x = remaining[0];
                                    remaining.RemoveAt(0);
                                    anchor.Add(new Tuple <int, Graphs.Vector>(x, modifiedLayout[x]));
                                }
                            }
                        }
                    }
                }
            }

            return(modifiedLayout);
        }