예제 #1
0
        public void Find_shortest_path_in_graph()
        {
            using (var reader = File.OpenText(@"C:\rajiv\DSinCS\DataStructures\DSTests\Data\tinyEWD.txt"))
            {
                var V = uint.Parse(reader.ReadLine());
                var g = new DGraph<int>(V);
                reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if(line == null) { continue; }
                    var inp = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    var u = int.Parse(inp[0]);
                    var v = int.Parse(inp[1]);
                    var w = float.Parse(inp[2]);
                    g.AddEdge(u, v, w);
                }
                var res = g.ShortestPathTree(0);
                Assert.AreEqual(res[0], 0);
                Assert.AreEqual(res[1], (float)1.05);
                Assert.AreEqual(res[2], (float)0.26);
                Assert.AreEqual(res[3], (float)0.99);
                Assert.AreEqual(res[4], (float)0.38);
                Assert.AreEqual(res[5], (float)0.73);
                Assert.AreEqual(res[6], (float)1.51);
                Assert.AreEqual(res[7], (float)0.6);

            }
        }
예제 #2
0
 public void DGraph_has_cycle()
 {
     DGraph<int> g = null;
     using (var reader = File.OpenText(@"C:\rajiv\DSinCS\DataStructures\DSTests\graph1.txt"))
         while (!reader.EndOfStream)
         {
             var V = uint.Parse(reader.ReadLine().Trim());
             g = new DGraph<int>(V);
             while (!reader.EndOfStream)
             {
                 var inp = reader.ReadLine().Split(new char[] { ' ' }).Select(int.Parse).ToArray();
                 g.AddEdge(inp[0], inp[1]);
             }
         }
     foreach (var e in g.BfsPathTo(0, 9))
     {
         Console.WriteLine($"{e} ");
     }
     foreach (var e in g.DfsPathTo(0, 4))
     {
         Console.WriteLine($"{e} ");
     }
     Console.WriteLine($"check cycle from a node 7 :{g.HasCycle(7)}");
     Console.WriteLine($"check cycle from a node 0 :{g.HasCycle(0)}");
     foreach (var e in g.DfsPathToNon(0, 4))
     {
         Console.WriteLine($"{e} ");
     }
 }
예제 #3
0
        static void Main(string[] args)
        {
            // построили граф с картинки
              var graph = DataGenerator.GenerateGraph();

              //graph.MakeEdgesDouble();
              graph.FindDistances(graph.Vertices.First());

              // хотим использовать Йена для 1ой и 5ой вершины и k = 3;
              // завели список кратчайших путей
              var listShortestWays = new List<Path<Edge<DVertex>,DVertex>>();
              var k = 5;

              // нашли первый кратчайший путь
              var shortestWay = graph.Vertices.First(x => x.Name == "5").Path;
              listShortestWays.Add(shortestWay);
              for (int i = 0; i < k - 1; i++)
              {
            var min = int.MaxValue;
            var newPath = new Path<Edge<DVertex>, DVertex>();

            // запомним версию графа без какого-то ребра
            var graphSlot = new DGraph();

            foreach (var edge in shortestWay.Edges)
            {
              // Построить новый граф полученный из исходного удалением текущего ребра.
              var graphWithoutEdge = graph.RemoveEdge(edge);

              // Найти кратчайший путь в построенном графе.
              graphWithoutEdge.FindDistances(graphWithoutEdge.Vertices.First());
              var newShortestWay = graphWithoutEdge.Vertices.First(x => x.Name == "5").Path;
              if (newShortestWay.Length > 0 && newShortestWay.Length < min)
              {
            min = newShortestWay.Length;
            newPath = newShortestWay;
            graphSlot = graphWithoutEdge;
              }
            }
            // если удалять больше нечего
            if (newPath.Length == 0)
              break;
            // Записать НОВЫЙ ПУТЬ в список кратчайших
            listShortestWays.Add(newPath);
            graph = graphSlot;
            // КРАТЧАЙШИЙ ПУТЬ = НОВЫЙ ПУТЬ
            shortestWay = newPath;
              }
        }
예제 #4
0
        private void CreateNestedGraph()
        {
            var g = GraphControlForNesting.Graph;

            // Create first nested graph.
            var inner1 = new DGraph()
            {
                Name = "Inner 1"
            };
            var node11    = inner1.AddNode("ID1.1");
            var node12    = inner1.AddNode("ID1.2");
            var edge11_12 = inner1.AddEdgeBetweenNodes(node11, node12);

            // Create second nested graph.
            var inner3 = new DGraph()
            {
                Name = "Inner 2"
            };
            var node31    = inner3.AddNode("ID3.1");
            var node32    = inner3.AddNode("ID3.2");
            var edge31_32 = inner3.AddEdgeBetweenNodes(node31, node32);

            // Create outer graph.
            var node1 = g.AddNode("ID1");

            node1.Label = new DNestedGraphLabel(node1, inner1);
            node1.DrawingNode.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Box;
            var node2 = g.AddNode("ID2");
            var node3 = g.AddNode("ID3");

            node3.Label = new DNestedGraphLabel(node3, inner3);
            node3.DrawingNode.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Box;
            var edge1_2 = g.AddEdgeBetweenNodes(node1, node2);
            var edge2_3 = g.AddEdgeBetweenNodes(node2, node3);

            // Set some labels.
            node11.Label = new DTextLabel(node11)
            {
                Text = "Node 1.1"
            };
            node12.Label = new DTextLabel(node12)
            {
                Text = "Node 1.2"
            };
            node31.Label = new DTextLabel(node31)
            {
                Text = "Node 3.1"
            };
            node32.Label = new DTextLabel(node32)
            {
                Text = "Node 3.2"
            };
            node2.Label = new DTextLabel(node2)
            {
                Text = "Node 2"
            };

            DEdge crossEdge1 = g.AddEdgeBetweenNodes(node11, node3);

            crossEdge1.Label = new DTextLabel(crossEdge1, "cross edge");
            DEdge crossEdge2 = g.AddEdgeBetweenNodes(node12, node31);

            g.BeginLayout();
        }
예제 #5
0
        private void Nesting_CreateProliferationGraph(DGraph graph)
        {
            DNode inNode = graph.AddNode("Pr_in");

            inNode.DrawingNode.Attr.Shape     = MsaglShape.Circle;
            inNode.DrawingNode.Attr.FillColor = MsaglColor.Red;

            DNode mitosisNode      = Nesting_Cell_AddNode(graph, "Pr_mitosis", null);
            Grid  mitosisContainer = new Grid();

            mitosisContainer.RowDefinitions.Add(new RowDefinition());
            mitosisContainer.RowDefinitions.Add(new RowDefinition());
            mitosisContainer.Children.Add(new TextBlock()
            {
                Text = "Mitosis", TextAlignment = TextAlignment.Center, FontWeight = FontWeights.Bold
            });
            mitosisNode.Label = new DNestedGraphLabel(mitosisNode, mitosisContainer);
            DGraph mitosisGraph = new DGraph(mitosisNode.Label as DNestedGraphLabel)
            {
                Name = "Mitosis"
            };

            Nesting_CreateMitosisGraph(mitosisGraph);
            Grid.SetRow(mitosisGraph, 1);
            mitosisContainer.Children.Add(mitosisGraph);
            (mitosisNode.Label as DNestedGraphLabel).Graphs.Add(mitosisGraph);

            DNode splitterNode = graph.AddNode("Pr_sp");

            splitterNode.DrawingNode.Attr.Shape     = MsaglShape.Circle;
            splitterNode.DrawingNode.Attr.FillColor = MsaglColor.Blue;

            DNode meiosisNode      = Nesting_Cell_AddNode(graph, "Pr_meiosis", null);
            Grid  meiosisContainer = new Grid();

            meiosisContainer.RowDefinitions.Add(new RowDefinition());
            meiosisContainer.RowDefinitions.Add(new RowDefinition());
            meiosisContainer.Children.Add(new TextBlock()
            {
                Text = "Meiosis", TextAlignment = TextAlignment.Center, FontWeight = FontWeights.Bold
            });
            meiosisNode.Label = new DNestedGraphLabel(meiosisNode, meiosisContainer);
            DGraph meiosisGraph = new DGraph(meiosisNode.Label as DNestedGraphLabel)
            {
                Name = "Meiosis"
            };

            Nesting_CreateMeiosisGraph(meiosisGraph);
            Grid.SetRow(meiosisGraph, 1);
            meiosisContainer.Children.Add(meiosisGraph);
            (meiosisNode.Label as DNestedGraphLabel).Graphs.Add(meiosisGraph);

            Nesting_Cell_AddEdge(graph, inNode, mitosisNode, null);
            Nesting_Cell_AddEdge(graph, mitosisNode, splitterNode, "Early Meiosis");

            DEdge splitter_g0_edge = graph.AddEdgeBetweenNodes(splitterNode, mitosisGraph.NodeMap["Mi_g0"]);

            splitter_g0_edge.DrawingEdge.Attr.Color = MsaglColor.Red;
            DEdge splitter_inter_edge = graph.AddEdgeBetweenNodes(splitterNode, meiosisGraph.NodeMap["Me_inter"]);

            splitter_inter_edge.DrawingEdge.Attr.Color = MsaglColor.Red;//*/
        }
예제 #6
0
        internal static void BeginLayout(DGraph graph)
        {
            NestedGraphHelper helper = new NestedGraphHelper(graph);

            helper.BeginLayout();
        }
예제 #7
0
 private NestedGraphHelper(DGraph graph)
 {
     m_Graph = graph;
 }
예제 #8
0
 private bool CheckNewCommunity(DGraph graph)
 {
     throw new NotImplementedException();
 }
예제 #9
0
 public ContentEditorProvider(DGraph owner)
 {
     Owner = owner;
 }
예제 #10
0
        public Tuple <int, Dictionary <Edge, MSAGLColor> > Execute(DGraph graph)
        {
            Tuple <int, Dictionary <Edge, MSAGLColor> > result;
            Dictionary <Edge, MSAGLColor> edgeColorMap = new Dictionary <Edge, MSAGLColor>();
            var independentSets = FindIndependentSets(graph);
            List <Tuple <byte, byte, byte> > usedColors = new List <Tuple <byte, byte, byte> >();
            Random rand = new Random();
            Tuple <byte, byte, byte> randomColor;

            foreach (List <Node> set in independentSets)
            {
                foreach (Node n in set)
                {
                    foreach (Edge nEdge in n.Edges)
                    {
                        do
                        {
                            randomColor =
                                new Tuple <byte, byte, byte>((byte)rand.Next(255), (byte)rand.Next(255), (byte)rand.Next(255));
                        } while (usedColors.Contains(randomColor));

                        MSAGLColor currentColor = new MSAGLColor(randomColor.Item1, randomColor.Item2, randomColor.Item3);
                        if (!edgeColorMap.ContainsKey(nEdge))
                        {
                            edgeColorMap.Add(nEdge, currentColor);
                            usedColors.Add(randomColor);
                        }
                        else
                        {
                            currentColor = edgeColorMap[nEdge];
                        }
                        foreach (Node m in set)
                        {
                            if (n != m)
                            {
                                Edge mEdge = null;
                                try
                                {
                                    mEdge = m.Edges.First(edge => !edgeColorMap.ContainsKey(edge) && !nEdge.isAdjasentTo(edge));
                                }
                                catch { }
                                finally
                                {
                                    if (mEdge != null && edgeColorMap.Count(pair => nEdge.isAdjasentTo(mEdge)) == 0 &&
                                        edgeColorMap.Count(pair => pair.Key.isAdjasentTo(mEdge) && pair.Value == currentColor) == 0)
                                    {
                                        edgeColorMap.Add(mEdge, currentColor);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            var remainingEdges = graph.Edges.Where(edge => !edgeColorMap.ContainsKey(edge));

            foreach (Edge e in remainingEdges)
            {
                do
                {
                    randomColor =
                        new Tuple <byte, byte, byte>((byte)rand.Next(255), (byte)rand.Next(255), (byte)rand.Next(255));
                } while (usedColors.Contains(randomColor));
                usedColors.Add(randomColor);
                edgeColorMap.Add(e, new MSAGLColor(randomColor.Item1, randomColor.Item2, randomColor.Item3));
            }
            result = new Tuple <int, Dictionary <Edge, MSAGLColor> >(usedColors.Count, edgeColorMap);
            return(result);
        }
예제 #11
0
        public void Run_topologocal_sort()
        {
            var g = new DGraph<int>(6);
            g.AddEdge(2, 3);
            g.AddEdge(3, 1);
            g.AddEdge(5, 2);
            g.AddEdge(4, 0);
            g.AddEdge(4, 1);
            g.AddEdge(5, 0);

            var res = g.TopologicalSort();
            var str = string.Join(",", res);
            Debug.WriteLine(str);
            Assert.AreEqual(str, "4,5,0,2,3,1");
        }
예제 #12
0
        public void Run_topological_sort_2()
        {
            var g = new DGraph<int>(8);
            g.AddEdge(5, 11);
            g.AddEdge(11, 2);
            g.AddEdge(11, 9);
            g.AddEdge(11, 10);
            g.AddEdge(7, 11);
            g.AddEdge(7, 8);
            g.AddEdge(8, 9);
            g.AddEdge(3, 8);
            g.AddEdge(3, 10);

            var res = g.TopologicalSort();
            var str = string.Join(",", res);
            Debug.WriteLine(str);
            Assert.AreEqual(str, "3,7,8,5,11,10,9,2");
        }
예제 #13
0
        public void MST_via_kruskals()
        {
            using (var reader = File.OpenText(@"C:\rajiv\DSinCS\DataStructures\DSTests\Data\tinyEWG.txt"))
            {
                var V = uint.Parse(reader.ReadLine());
                var g = new DGraph<int>(V);
                reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (line == null) { continue; }
                    var inp = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    var u = int.Parse(inp[0]);
                    var v = int.Parse(inp[1]);
                    var w = float.Parse(inp[2]);
                    g.AddEdge(u, v, w);
                }
                var res = g.MST_Kruskal();
                Assert.AreEqual(res.Count, 7);

            }
        }
예제 #14
0
 private void VisitNode(DGraph graph)
 {
     throw new NotImplementedException();
 }
        private void _CalculateEdgeBetweenness(DGraph subgraph)
        {
            if (subgraph == null)
            {
                return;
            }
            int n   = subgraph.Nodes.Count;
            int MAX = int.MaxValue;

            foreach (Node s in subgraph.Nodes)
            {
                foreach (Edge e in s.AdjacencyEdges)
                {
                    edgeBetweenness[e] = 0;
                }
            }

            foreach (Node s in subgraph.Nodes)
            {
                Queue <Node> Q = new Queue <Node>();
                Stack <Node> S = new Stack <Node>();
                Dictionary <Node, List <Node> > pred = new Dictionary <Node, List <Node> >();

                Dictionary <Node, int>    dist  = new Dictionary <Node, int>();
                Dictionary <Node, int>    sigma = new Dictionary <Node, int>();
                Dictionary <Node, double> delta = new Dictionary <Node, double>();

                // initialization
                foreach (Node d in subgraph.Nodes)
                {
                    dist.Add(d, MAX);
                    sigma.Add(d, 0);
                    delta.Add(d, 0);
                    pred.Add(d, new List <Node>());
                }

                dist[s]  = 0;
                sigma[s] = 1;
                Q.Enqueue(s);

                // while
                while (Q.Count != 0)
                {
                    Node v = Q.Dequeue();
                    S.Push(v);

                    // sửa chỗ này lại, không duyệt hết mà chỉ duyệt 1 số thôi
                    foreach (Node w in v.AdjacencyNodes)
                    {
                        if (dist[w] == MAX)
                        {
                            dist[w] = dist[v] + 1;
                            Q.Enqueue(w);
                        }
                        if (dist[w] == dist[v] + 1)
                        {
                            sigma[w] = sigma[w] + sigma[v];
                            pred[w].Add(v);
                        }
                    }
                }

                // accumuation
                while (S.Count != 0)
                {
                    Node w = S.Pop();
                    foreach (Node v in pred[w])
                    {
                        double c = ((double)(sigma[v]) / sigma[w]) * (1.0 + delta[w]);

                        // tim canh
                        Edge e = graph.FindEdge(v, w);
                        edgeBetweenness[e] += c;

                        delta[v] += c;
                    }
                }
            }
        }
예제 #16
0
 private void setRelation(int start, int end, float price, DGraph <GameObject> myGraph)
 {
     myGraph.SetRelationShip(start, end, price);
 }
예제 #17
0
        // Пример отсюда https://ru.wikipedia.org/wiki/%D0%90%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC_%D0%94%D0%B5%D0%B9%D0%BA%D1%81%D1%82%D1%80%D1%8B
        public static DGraph GenerateGraph()
        {
            DVertex one = new DVertex { Name = "1"};
              DVertex two = new DVertex {Name = "2"};
              DVertex three = new DVertex {Name = "3"};
              DVertex four = new DVertex {Name = "4"};
              DVertex five = new DVertex {Name = "5"};
              DVertex six = new DVertex {Name = "6"};

              var edges = new List<Edge<DVertex>>
              {
            new Edge<DVertex>
            {
              X = one,
              Y = two,
              Weight = 7
            },
            new Edge<DVertex>
            {
              X = one,
              Y = three,
              Weight = 9
            },
            new Edge<DVertex>
            {
              X = one,
              Y = six,
              Weight = 14
            },
            new Edge<DVertex>
            {
              X = two,
              Y = three,
              Weight = 10
            },
            new Edge<DVertex>
            {
              X = two,
              Y = four,
              Weight = 15
            },
            new Edge<DVertex>
            {
              X = three,
              Y = four,
              Weight = 11
            },
            new Edge<DVertex>
            {
              X = three,
              Y = six,
              Weight = 2
            },
            new Edge<DVertex>
            {
              X = four,
              Y = five,
              Weight = 6
            },
            new Edge<DVertex>
            {
              X = five,
              Y = six,
              Weight = 9
            }
              };

              var vertices = new List<DVertex>();
              vertices.AddRange(new[] { one, two, three, four, five, six });

              var graph = new DGraph
              {
            Edges = edges,
            Vertices = vertices
              };

              return graph;
        }
예제 #18
0
        public CommunityStructure FindCommunityStructure(DGraph pGraph)
        {
            // Clone graph này ra để xử lý
            originalGraph = pGraph;
            graph         = pGraph.Clone();

            // Cộng đồng
            CommunityStructure tempCS = GetCommunityStructure();

            // Số cộng đồng
            int initCount      = tempCS.Count;
            int countCommunity = initCount;

            // Q
            _BestVAD = 0;
            _VAD     = 0;
            _BestM   = 0;
            _M       = 0;

            // Tính edge betweenness lần đầu
            CalculateEdgeBetweenness(tempCS);
            CalculateVertexBetweenness(tempCS);

            WriteLog("Start CONGA algorithm");
            // tính thuật toán
            while (true)
            {
                while (countCommunity <= initCount)
                {
                    // Tìm tập hợp các đỉnh có vertex betweenness lớn hơn max edge betweenness:
                    // Thật chất là tìm max edge betweenness và max vertext betweenness
                    // Xóa cạnh có edge betweenness lớn nhất
                    RemoveEdgeOrSplitVertex(tempCS);

                    // Đếm lại số cộng đồng
                    tempCS = GetCommunityStructure();

                    countCommunity = tempCS.Count;

                    CalculateEdgeBetweenness(tempCS);
                    CalculateVertexBetweenness(tempCS);
                }

                initCount = countCommunity;

                // Tính Q = VAD
                if (_UseVAD)
                {
                    _VAD = CalculateVAD(tempCS);

                    if (_VAD > _BestVAD)
                    {
                        _BestVAD = _VAD;
                        Cs       = tempCS;
                    }
                }
                else
                {
                    _M = CalculateModularity(tempCS, originalGraph);

                    if (_M > _BestM)
                    {
                        _BestM = _M;
                        Cs     = tempCS;
                    }
                }

                if (graph.Edges.Count == 0)
                {
                    break;
                }
            }

            return(this.Cs);
        }
예제 #19
0
        static void Main(string[] args)
        {
            // Precedence Seq input
            List <string[]> d = new List <string[]>();

            for (int i = 0; i < 17; i++)
            {
                string s = Console.ReadLine();

                string[] ssv = s.Split(' ');
                d.Add(ssv);
            }

            foreach (var item in d)
            {
                Console.WriteLine(">>> {0} {1}", item[0], item[1]);
            }

            // Time Seq input
            List <KeyValuePair <int, float> > ts = new List <KeyValuePair <int, float> >();

            for (int i = 0; i < 15; i++)
            {
                ts.Add(new KeyValuePair <int, float>(i + 1,
                                                     float.Parse(Console.ReadLine())));
            }

            foreach (var item in ts)
            {
                Console.WriteLine(string
                                  .Format("I: {0} ST: {1}",
                                          item.Key, item.Value));
            }

            Console.WriteLine();

            DataParser dp = new DataParser(d, ts);
            DGraph     dg = dp.ParseData();

            // Graph output
            foreach (var item in dg.Vertices)
            {
                int   i = item.ID;
                float f = item.StandardTime;
                Console.WriteLine("I: {0} , ST : {1}", i, f);
            }

            Console.WriteLine();

            DGraph g      = dg;
            DGraph output = dp.PerformRPWDist(g);

            // RPW graph output
            foreach (var item in output.Vertices)
            {
                int   i = item.ID;
                float f = item.StandardTime;
                Console.WriteLine("I: {0} , Sum : {1}", i, f);
            }

            List <Vertex> v          = output.Vertices;
            List <Vertex> sortedList = v.OrderByDescending(vtx => vtx.StandardTime).ToList();

            foreach (var item in sortedList)
            {
                Console.WriteLine("Index: {0},  Sum: {1}", item.ID, item.StandardTime);
            }

            // LcR data
            List <KeyValuePair <int, float> > rpwTimeSeq = new List <KeyValuePair <int, float> >();

            for (int i = 0; i < sortedList.Count; i++)
            {
                int index =
                    sortedList[i].ID;
                float st = ts
                           .Find(kvp => kvp.Key == index).Value;

                KeyValuePair <int, float> rpwKvp = new KeyValuePair <int, float>(index, st);
                rpwTimeSeq.Add(rpwKvp);
            }

            foreach (var item in rpwTimeSeq)
            {
                Console.WriteLine(item.Key + " " + item.Value);
            }


            Console.ReadLine();
        }
예제 #20
0
 private CommunityStructure FindStructureWithMaxClique(DGraph graph)
 {
     return(null);
 }