Exemplo n.º 1
0
    	//DC this version was using the old QuickGraph MarkedEdge
        public static void createGraphWizDotFile(AdjacencyGraph<String, TaggedEdge<String, String>> gGraphWizToPopulate,
                                                 TreeNode tnTreeNode, bool bOrder, bool bFilterName, bool bFilterClass,
                                                 int iFilterClassLevel)
        {
            if (bFilterClass)
                tnTreeNode.Text = FilteredSignature.filterName(tnTreeNode.Text, false, false, true, 0, true, true,
                                                               iFilterClassLevel);
            TaggedEdge<String, string> meTemp;
            if (gGraphWizToPopulate.ContainsVertex(tnTreeNode.Text))
            {
            }
            else
                gGraphWizToPopulate.AddVertex(tnTreeNode.Text);

            foreach (TreeNode tnChild in tnTreeNode.Nodes)
            {
                if (bFilterClass)
                    tnChild.Text = FilteredSignature.filterName(tnChild.Text, false, false, true, 0, true, true,
                                                                iFilterClassLevel);
                createGraphWizDotFile(gGraphWizToPopulate, tnChild, bOrder, bFilterName, bFilterClass, iFilterClassLevel);
                if (bOrder)
                {
                    if (false == gGraphWizToPopulate.TryGetEdge(tnTreeNode.Text, tnChild.Text, out meTemp))
                        gGraphWizToPopulate.AddEdge(new TaggedEdge<String, string>(tnTreeNode.Text, tnChild.Text,
                                                                                   "marker"));
                }
                else if (false == gGraphWizToPopulate.TryGetEdge(tnChild.Text, tnTreeNode.Text, out meTemp))
                    gGraphWizToPopulate.AddEdge(new TaggedEdge<String, string>(tnChild.Text, tnTreeNode.Text, "marker"));

                //gGraphToPopulate.AddEdge(tnTreeNode.Text, tnChild.Text);
                //    gGraphToPopulate.AddEdge(Analysis_CallFlow.display.filterName(tnChild.Text, false, false, false), Analysis_CallFlow.display.filterName(tnTreeNode.Text, false, false, false));
                //else
            }
        }
        public void CheckPredecessorLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            Edge<int> e12 = new Edge<int>(1, 2); g.AddEdge(e12);
            Edge<int> e23 = new Edge<int>(2, 3); g.AddEdge(e23);

            var dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, e => 1);
            var vis = new VertexPredecessorRecorderObserver<int, Edge<int>>();
            using(vis.Attach(dij))
                dij.Compute(1);

            IEnumerable<Edge<int>> path;
            Assert.IsTrue(vis.TryGetPath(2, out path));
            var col = path.ToList();
            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(e12, col[0]);

            Assert.IsTrue(vis.TryGetPath(3, out path));
            col = path.ToList();
            Assert.AreEqual(2, col.Count);
            Assert.AreEqual(e12, col[0]);
            Assert.AreEqual(e23, col[1]);
        }
Exemplo n.º 3
0
		public void Removing_Explicit_Edges_2()
		{
			var graph = new AdjacencyGraph<int, Edge<int>>();
			graph.AddVertex(1);
			graph.AddVertex(2);
			graph.AddVertex(3);
			graph.AddVertex(4);
			graph.AddVertex(5);
			graph.AddVertex(6);
			graph.AddVertex(7);
			graph.AddEdge(new Edge<int>(1, 3));
			graph.AddEdge(new Edge<int>(1, 4));
			graph.AddEdge(new Edge<int>(1, 6));
			graph.AddEdge(new Edge<int>(3, 6));
			graph.AddEdge(new Edge<int>(4, 6));
			graph.AddEdge(new Edge<int>(2, 4));
			graph.AddEdge(new Edge<int>(2, 5));
			graph.AddEdge(new Edge<int>(2, 7));
			graph.AddEdge(new Edge<int>(4, 7));
			graph.AddEdge(new Edge<int>(5, 7));

			GraphHelper.RemoveExplicitEdges(graph);

			Assert.AreEqual(8, graph.EdgeCount);
			Assert.IsTrue(graph.ContainsEdge(1, 3));
			Assert.IsTrue(graph.ContainsEdge(1, 4));
			Assert.IsTrue(graph.ContainsEdge(2, 4));
			Assert.IsTrue(graph.ContainsEdge(2, 5));
			Assert.IsTrue(graph.ContainsEdge(3, 6));
			Assert.IsTrue(graph.ContainsEdge(4, 6));
			Assert.IsTrue(graph.ContainsEdge(4, 7));
			Assert.IsTrue(graph.ContainsEdge(5, 7));
		}
        public void TwoVertexCycle()
        {
            AdjacencyGraph<string, Edge<string>> g = new AdjacencyGraph<string, Edge<string>>(true);
            g.AddVertex("v1");
            g.AddVertex("v2");
            g.AddEdge(new Edge<string>("v1", "v2"));
            g.AddEdge(new Edge<string>("v2", "v1"));
            StronglyConnectedComponentsAlgorithm<string, Edge<String>> strong = new StronglyConnectedComponentsAlgorithm<string, Edge<String>>(g);
            strong.Compute();
            Assert.AreEqual(1, strong.ComponentCount);

            checkStrong(strong);
        }
Exemplo n.º 5
0
		public void Removing_Explicit_Edges_1()
		{
			var graph = new AdjacencyGraph<int, Edge<int>>();
			graph.AddVertex(1);
			graph.AddVertex(2);
			graph.AddVertex(3);
			graph.AddEdge(new Edge<int>(1, 2));
			graph.AddEdge(new Edge<int>(2, 3));
			graph.AddEdge(new Edge<int>(1, 3));

			GraphHelper.RemoveExplicitEdges(graph);

			Assert.AreEqual(2, graph.EdgeCount);
			Assert.IsTrue(graph.ContainsEdge(1, 2));
			Assert.IsTrue(graph.ContainsEdge(2, 3));
		}
Exemplo n.º 6
0
        public void GenerateDotFile()
        {
            var graph = new AdjacencyGraph<string, TaggedEdge<string, string>>();

            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                graph.AddVertex(String.Format("{0}", i));
            }
            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                for (int j = 0; j < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); j++)
                {
                    if ((m_Matrix[i, j] == true) & (i < j))
                    {
                        graph.AddEdge(new TaggedEdge<string, string>(String.Format("{0}", i), String.Format("{0}", j), String.Format("{0}", i)));
                    }
                }
            }

            var graphViz = new GraphvizAlgorithm<string, TaggedEdge<string, string>>(graph, @".\", QuickGraph.Graphviz.Dot.GraphvizImageType.Png);
            graphViz.FormatVertex += (sender, e) =>
            {
                e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Circle;
            };

            graphViz.FormatEdge += (sender, e) =>
            {
                e.EdgeFormatter.Dir = QuickGraph.Graphviz.Dot.GraphvizEdgeDirection.None;
            };

            graphViz.Generate(new FileDotEngine(), m_Name);
        }
Exemplo n.º 7
0
        public static AdjacencyGraph<PropertyInfo, STaggedEdge<PropertyInfo, string>> BuildDependencyGraph(Type viewModelType)
        {
            var directDependencies = ViewModelConventions.GetViewModelProperties(viewModelType).ToDictionary(p => p, GetDirectDependentProperties);

            var graph = new AdjacencyGraph<PropertyInfo, STaggedEdge<PropertyInfo, string>>();

            foreach (var directDependency in directDependencies)
            {
                var property = directDependency.Key;
                graph.AddVertex(property);

                foreach (var dependentProperty in directDependency.Value)
                {
                    var sub = dependentProperty.SubPath;
                    var propertyType = property.PropertyType;
                    if (GetCollectionType(propertyType) != null) propertyType = GetCollectionType(propertyType);

                    if (String.IsNullOrEmpty(sub) && ViewModelConventions.IsViewModel(propertyType))
                        sub = "*";

                    graph.AddEdge(new STaggedEdge<PropertyInfo, string>(property, dependentProperty.Property, sub));
                }
            }

            return graph;
        }
Exemplo n.º 8
0
        public static AdjacencyGraph<PropertyInfo, STaggedEdge<PropertyInfo, string>> BuildDependencyGraph(IEnumerable<Type> viewModelTypes)
        {
            var graph = new AdjacencyGraph<PropertyInfo, STaggedEdge<PropertyInfo, string>>();

            foreach (var dependencyGraphWithinViewModel in viewModelTypes.Select(BuildDependencyGraph))
            {
                dependencyGraphWithinViewModel.Vertices.ForEach(v => graph.AddVertex(v));
                dependencyGraphWithinViewModel.Edges.ForEach(e => graph.AddEdge(e));
            }

            while (graph.Edges.Any(e => !String.IsNullOrEmpty(e.Tag)))
            {
                var edge = graph.Edges.First(e => !String.IsNullOrEmpty(e.Tag));

                var index = edge.Tag.IndexOf(".");
                var path = index < 0 ? edge.Tag : edge.Tag.Substring(0, index);
                var rest = index < 0 ? null : edge.Tag.Substring(index + 1);

                var propertyType = edge.Source.PropertyType;
                if (GetCollectionType(propertyType) != null) propertyType = GetCollectionType(propertyType);

                if (path != "*")
                {
                    var property = ViewModelConventions.GetViewModelProperties(propertyType).FirstOrDefault(p => p.Name == path);
                    if (property != null)
                    {
                        graph.AddEdge(new STaggedEdge<PropertyInfo, string>(property, edge.Target, rest));
                    }
                    else
                    {
                        ViewModelConventions.Log.Warn(String.Format("Could not resolve '{0}' on '{1}'.", path, propertyType));
                    }
                }
                else
                {
                    var properties = ViewModelConventions.GetViewModelProperties(propertyType).ToList();
                    properties.ForEach(p => graph.AddEdge(new STaggedEdge<PropertyInfo, string>(p, edge.Target, rest)));
                }

                graph.RemoveEdge(edge);
            }

            var edges = graph.Edges.ToArray();
            graph.RemoveVertexIf(v => !edges.Any(e => e.Source == v || e.Target == v));

            return graph;
        }
        public void RunOnLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            g.AddEdge(new Edge<int>(1,2));
            g.AddEdge(new Edge<int>(2,3));

            var dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, e => 1);
            dij.Compute(1);

            Assert.AreEqual<double>(0, dij.Distances[1]);
            Assert.AreEqual<double>(1, dij.Distances[2]);
            Assert.AreEqual<double>(2, dij.Distances[3]);
        }
        public void RunOnDoubleLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            Edge<int> e12 = new Edge<int>(1, 2); g.AddEdge(e12);
            Edge<int> e23 = new Edge<int>(2, 3); g.AddEdge(e23);
            Edge<int> e13 = new Edge<int>(1, 3); g.AddEdge(e13);

            var dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, e => 1);
            dij.Compute(1);

            Assert.AreEqual(0.0, dij.Distances[1]);
            Assert.AreEqual(1.0, dij.Distances[2]);
            Assert.AreEqual(1.0, dij.Distances[3]);
        }
Exemplo n.º 11
0
        public static FloydWarshallAllShortestPathAlgorithm<int, UndirectedEdge<int>> ComputeShortestPaths(Dictionary<int, Node> nodes, IEnumerable<Edge> edges)
        {
            var graph = new AdjacencyGraph<int, UndirectedEdge<int>>();
            foreach (int nodeId in nodes.Keys)
            {
                graph.AddVertex(nodeId);
            }
            foreach (Edge edge in edges)
            {
                graph.AddEdge(new UndirectedEdge<int>(edge.StartNodeId, edge.EndNodeId));
                graph.AddEdge(new UndirectedEdge<int>(edge.EndNodeId, edge.StartNodeId));
            }

            Func<UndirectedEdge<int>, double> edgeCost = e => GetEdgeCost(nodes, e);
            var pathFinder = new FloydWarshallAllShortestPathAlgorithm<int, UndirectedEdge<int>>(graph, edgeCost);
            pathFinder.Compute();
            return pathFinder;
        }
 public void OneTwo()
 {
     var graph = new AdjacencyGraph<int, Edge<int>>();
     graph.AddVertex(1);
     graph.AddVertex(2);
     graph.AddEdge(new Edge<int>(1, 2));
     var t = new TopologicalSortAlgorithm<int, Edge<int>>(graph);
     t.Compute();
 }
Exemplo n.º 13
0
        //graph, tgraph, sourceNode, endNode, weight
        public static void AddEdgeToBoth(AdjacencyGraph<string, Edge<string>> graph, AdjacencyGraph<string, Edge<string>> tGraph, Dictionary<Edge<string>, double> edgeCost, Dictionary<Edge<string>, double> tEdgeCost, string sourceString, string endString, int weight)
        {
            Edge<string> curEdge = new Edge<string>(sourceString, endString);
            graph.AddEdge(curEdge);
            edgeCost.Add(curEdge, weight);

            Edge<string> transposeEdge = new Edge<string>(endString, sourceString);
            tGraph.AddEdge(transposeEdge);
            tEdgeCost.Add(transposeEdge, weight);
        }
        public void RunOnLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            g.AddEdge(new Edge<int>(1,2));
            g.AddEdge(new Edge<int>(2,3));

            Dictionary<Edge<int>,double> weights = 
                DijkstraShortestPathAlgorithm<int,Edge<int>>.UnaryWeightsFromEdgeList(g);
            DijkstraShortestPathAlgorithm<int, Edge<int>> dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, weights);
            dij.Compute(1);

            Assert.AreEqual<double>(0, dij.Distances[1]);
            Assert.AreEqual<double>(1, dij.Distances[2]);
            Assert.AreEqual<double>(2, dij.Distances[3]);
        }
        public void RootIsNotAccessible()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(0);
            g.AddVertex(1);
            g.AddEdge(new Edge<int>(0, 1));

            target = new CyclePoppingRandomTreeAlgorithm<int, Edge<int>>(g);
            target.RandomTreeWithRoot(0);
        }
        public void IncrementalConnectedComponent()
        {
            var g = new AdjacencyGraph<int, SEquatableEdge<int>>();
            g.AddVertexRange(new int[] { 0, 1, 2, 3 });
            var components = AlgorithmExtensions.IncrementalConnectedComponents(g);

            var current = components();
            Assert.AreEqual(4, current.Key);

            g.AddEdge(new SEquatableEdge<int>(0, 1));
            current = components();
            Assert.AreEqual(3, current.Key);

            g.AddEdge(new SEquatableEdge<int>(2, 3));
            current = components();
            Assert.AreEqual(2, current.Key);

            g.AddEdge(new SEquatableEdge<int>(1, 3));
            current = components();
            Assert.AreEqual(1, current.Key);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Znajduje wszystkie paterny dec
        /// </summary>
        /// <param name="g"></param>
        /// <returns></returns>
        public AdjacencyGraph<Node, Edge<Node>> FindDecisionPattern(AdjacencyGraph<Node, Edge<Node>> g)
        {
            List<Node> decisionNodes = g.Vertices.Where(x => x.Type == NodeType.DecisionNode).ToList();

            foreach (var decisionNode in decisionNodes)
            {
                var outEdges = g.OutEdges(decisionNode);
                var left = outEdges.ElementAt(0).Target;
                var right = outEdges.ElementAt(1).Target;

                var upperEdge = g.Edges.Where(x => x.Target == decisionNode).ToList().FirstOrDefault();

                if (g.OutEdges(left).Count() == 1 && g.OutEdges(right).Count() == 1 && (
                    g.OutEdges(left).ElementAt(0).Target == g.OutEdges(right).ElementAt(0).Target)
                    || g.OutEdges(left).ElementAt(0).Target == right
                    || g.OutEdges(right).ElementAt(0).Target == left
                    || left.Type==NodeType.ActivityFinalNode
                    || right.Type==NodeType.ActivityFinalNode)
                {
                    string name = "dec(" + decisionNode.Name + ", " + left.Name + ", " + right.Name + ")";
                    var decisionPattern = new Node(name, NodeType.DecisionPattern);

                    g.AddVertex(decisionPattern);
                    var nextNode = g.OutEdges(right).ElementAt(0).Target;
                    if(nextNode == left || nextNode==right)
                        nextNode = g.OutEdges(left).ElementAt(0).Target;

                    g.AddEdge(new Edge<Node>(upperEdge.Source, decisionPattern));
                    g.AddEdge(new Edge<Node>(decisionPattern, nextNode));

                    g.RemoveVertex(decisionNode);
                    g.RemoveVertex(left);
                    g.RemoveVertex(right);
                }
            }

            return g;
        }
        public static AdjacencyGraph<string, Edge<string>> GenerateGraph(IEnumerable<AssemblyInfo> assemblies, bool skipGacAssemblies = true)
        {
            // Detect all the GAC assemblies
            var gacAssemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
            if (skipGacAssemblies)
            {
                foreach (var info in assemblies)
                {
                    if (info.IsInGac)
                        gacAssemblies.Add(info.FullName);
                }
            }

            var graph = new AdjacencyGraph<string, Edge<string>>();
            var verticesOnGraph = new HashSet<string>();

            foreach (var parent in assemblies)
            {
                string parentName = parent.FullName;

                // Skip GAC assemblies
                if (gacAssemblies.Contains(parentName))
                    continue;

                if (!verticesOnGraph.Contains(parentName))
                {
                    graph.AddVertex(parent.Name);
                    verticesOnGraph.Add(parentName);
                }

                foreach (var child in parent.Children)
                {
                    string childName = child.FullName;
                    if (gacAssemblies.Contains(childName))
                        continue;

                    if (!verticesOnGraph.Contains(childName))
                    {
                        graph.AddVertex(child.Name);

                        verticesOnGraph.Add(childName);
                    }

                    // TODO: reduce two-way edges.  This may happen in a rare case of circular dependency.
                    graph.AddEdge(new Edge<string>(parent.Name, child.Name));
                }
            }
            return graph;
        }
Exemplo n.º 19
0
        public Region(string id, List<Waypoint> waypointList, List<Tuple<string, string>> connections,
			Size size, string miniMap, Point miniMapOffset, string worldMap, Point worldMapOffset, bool chokePoint)
        {
            ChokePoint = chokePoint;
            WorldMapOffset = worldMapOffset;
            WorldMap = worldMap;
            MiniMapOffset = miniMapOffset;
            MiniMap = miniMap;
            Size = size;
            Id = id;
            WaypointList = waypointList;
            Connections = connections;

            foreach (var wp in WaypointList)
            {
                wp.Region = this;
            }

            Waypoints = WaypointList.ToDictionary(x => x.Id.ToLowerInvariant());

            RegionGraph = new AdjacencyGraph<Waypoint, Connection>(true);
            RegionGraph.AddVertexRange(waypointList);

            foreach (var c in Connections)
            {
                var wp1 = Waypoints[c.Item1];
                var wp2 = Waypoints[c.Item2];

                var dist = Math.Sqrt(Math.Pow(wp1.Location.X - wp2.Location.X, 2) + Math.Pow(wp1.Location.Y - wp2.Location.Y, 2));

                var time = TimeSpan.FromSeconds(dist / BaseSpeed);

                RegionGraph.AddEdge(new Connection(wp1, wp2, time));
                RegionGraph.AddEdge(new Connection(wp2, wp1, time));
            }
        }
Exemplo n.º 20
0
        public void TwoOne()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            // Deliberately adding 1 and then 2, before adding edge (2, 1).
            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddEdge(new Edge <int>(2, 1));

            var algorithm = new TopologicalSortAlgorithm <int, Edge <int> >(graph);
            var vertices  = new List <int>(graph.VertexCount);

            algorithm.Compute(vertices);

            Assert.AreEqual(2, vertices.Count);
        }
Exemplo n.º 21
0
        public static void SaveToDot(StaticFlow sFlow, DynamicFlow dFlow, string filename)
        {
            AdjacencyGraph <string, TaggedEdge <string, string> > displayGraph = new AdjacencyGraph <string, TaggedEdge <string, string> >();

            foreach (string vertex in dFlow.Graph.Vertices)
            {
                displayGraph.AddVertex(vertex);
            }
            foreach (TaggedEdge <string, (bool Branch, StateUpdate StateUpdate)> edge in dFlow.Graph.Edges)
            {
                int    lineNumber  = dFlow.LineNumber(edge.Source);
                string displayInfo = sFlow.Get_Line_Str(lineNumber) + "\n" + edge.Tag.StateUpdate.ToString2();
                displayGraph.AddEdge(new TaggedEdge <string, string>(edge.Source, edge.Target, displayInfo));
            }
            Visualize(displayGraph, filename);
        }
        public void OneTwo()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddEdge(new Edge <int>(1, 2));

            var algorithm = new TopologicalSortAlgorithm <int, Edge <int> >(graph, graph.VertexCount);

            algorithm.Compute();

            CollectionAssert.AreEqual(
                new[] { 1, 2 },
                algorithm.SortedVertices);
        }
Exemplo n.º 23
0
        private AdjacencyGraph <PathNode, PathEdge> BuildRoutingGraph(
            IEnumerable <PathNode> nodes,
            IEnumerable <PathEdge> edges)
        {
            var graph = new AdjacencyGraph <PathNode, PathEdge>();

            foreach (var node in nodes)
            {
                graph.AddVertex(node);
            }
            foreach (var edge in edges)
            {
                graph.AddEdge(edge);
            }
            return(graph);
        }
Exemplo n.º 24
0
        private AdjacencyGraph<Node, Edge<Node>> CreateGraphFromNode(XDocument xDocument, XNode parent)
        {
            var graph = new AdjacencyGraph<Node, Edge<Node>>();

            var nodes = xDocument.Descendants().Where(x => x.Parent != null && (x.Parent.Parent != null && (x.Parent != null && x.Parent.Parent.Parent == parent)));

            var fromList = nodes.Where(x => x.Parent != null && (x.Name.LocalName == "ControlFlow" && x.Parent.Name.LocalName =="FromSimpleRelationships") );
            var toList = nodes.Where(x => x.Parent != null && (x.Name.LocalName == "ControlFlow" && x.Parent.Name.LocalName =="ToSimpleRelationships") );
            foreach (var fromNode in fromList)
            {
                var xNode1 = fromNode.Parent.Parent;

                string idref = fromNode.Attribute("Idref").Value;
                var xNode2 =
                    toList.Where(x => x.Parent != null && (x.Attribute("Idref").Value.ToString() == idref))
                        .Select(x => x.Parent.Parent).FirstOrDefault();

                if (xNode1 == null || xNode2 == null)
                    continue;

                Node node1 = new Node(xNode1.Attribute("Name").Value, GetNodeType(xNode1));
                Node node2 = new Node(xNode2.Attribute("Name").Value, GetNodeType(xNode2));

                if (!graph.Vertices.Any(x => x.Name==node1.Name && x.Type==node1.Type))
                {
                    graph.AddVertex(node1);
                }
                else
                {
                    node1 = graph.Vertices.FirstOrDefault(x => x.Name == node1.Name && x.Type == node1.Type);
                }
                if (!graph.Vertices.Any(x => x.Name == node2.Name && x.Type == node2.Type))
                {
                    graph.AddVertex(node2);
                }
                else
                {
                    node2 = graph.Vertices.FirstOrDefault(x => x.Name == node2.Name && x.Type == node2.Type);
                }
                var newEdge = new Edge<Node>(node1, node2);
                if(!graph.ContainsEdge(newEdge))
                    graph.AddEdge(newEdge);

            }

            return graph;
        }
Exemplo n.º 25
0
        public Graph CreateGraph(StateMachineGraphData data)
        {
            var graph = new AdjacencyGraph<Vertex, Edge<Vertex>>();

            data.Vertices.Each(x => graph.AddVertex(x));
            data.Edges.Each(x => graph.AddEdge(new Edge<Vertex>(x.From, x.To)));

            GleeGraphPopulator<Vertex, Edge<Vertex>> glee = graph.CreateGleePopulator();

            glee.NodeAdded += NodeStyler;
            glee.EdgeAdded += EdgeStyler;
            glee.Compute();

            Graph gleeGraph = glee.GleeGraph;

            return gleeGraph;
        }
        public void TransitiveReduction_IsolatedVertices()
        {
            const string vertex1 = "/test";
            const string vertex2 = "/test/123";
            const string vertex3 = "/test/notlinked";
            var          edge12  = new Edge <string>(vertex1, vertex2);

            var graph = new AdjacencyGraph <string, Edge <string> >();

            graph.AddVertexRange(new[] { vertex1, vertex2, vertex3 });
            graph.AddEdge(edge12);

            BidirectionalGraph <string, Edge <string> > result = graph.ComputeTransitiveReduction();

            AssertHasVertices(result, new[] { vertex1, vertex2, vertex3 });
            AssertHasEdges(result, new[] { edge12 });
        }
Exemplo n.º 27
0
        public Graph CreateGraph(PipelineGraphData data)
        {
            var graph = new AdjacencyGraph <Vertex, Edge <Vertex> >();

            data.Vertices.Each(x => graph.AddVertex(x));
            data.Edges.Each(x => graph.AddEdge(new Edge <Vertex>(x.From, x.To)));

            GleeGraphPopulator <Vertex, Edge <Vertex> > glee = graph.CreateGleePopulator();

            glee.NodeAdded += NodeStyler;
            glee.EdgeAdded += EdgeStyler;
            glee.Compute();

            Graph gleeGraph = glee.GleeGraph;

            return(gleeGraph);
        }
Exemplo n.º 28
0
        public Graph CreateGraph(IEnumerable<Vertex> vertices, IEnumerable<Graphing.Edge> edges)
        {
            var graph = new AdjacencyGraph<Vertex, Edge<Vertex>>();

            vertices.Each(x => graph.AddVertex(x));
            edges.Each(x => graph.AddEdge(new Edge<Vertex>(x.From, x.To)));

            GleeGraphPopulator<Vertex, Edge<Vertex>> glee = graph.CreateGleePopulator();

            glee.NodeAdded += NodeStyler;
            glee.EdgeAdded += EdgeStyler;
            glee.Compute();

            Graph gleeGraph = glee.GleeGraph;

            return gleeGraph;
        }
        /// <summary>
        /// Sorts the collection by evaluation order, using a topological sort.
        /// </summary>
        /// <param name="calcs">The collection to sort.</param>
        /// <returns>The sorted collection.</returns>
        public static IEnumerable<CalculationControl> SortByEvaluationOrder(this IEnumerable<CalculationControl> calcs)
        {
            AdjacencyGraph<CalculationControl, SEdge<CalculationControl>> graph = new AdjacencyGraph<CalculationControl, SEdge<CalculationControl>>();
            graph.AddVertexRange(calcs);
            foreach (var target in calcs)
            {
                foreach (var calc in calcs)
                {
                    if (target.CalculationExpression.Contains("{%" + calc.Name + "%}") || Regex.IsMatch(target.CalculationExpression, @"{%[^\.]*." + calc.Name + ".Total%}"))
                    {
                        graph.AddEdge(new SEdge<CalculationControl>(calc, target));
                    }
                }
            }

            return graph.TopologicalSort();
        }
        public ToscaNodeTypeInheritanceWalker(ToscaCloudServiceArchive cloudServiceArchive, Action <string, ToscaNodeType> action)
        {
            nodeTypes = cloudServiceArchive.NodeTypes;
            graph     = new AdjacencyGraph <string, ToscaGraphEdge>();
            graph.AddVertexRange(cloudServiceArchive.NodeTypes.Select(_ => _.Key));
            foreach (var toscaNodeType in cloudServiceArchive.NodeTypes)
            {
                if (!toscaNodeType.Value.IsRoot())
                {
                    graph.AddEdge(new ToscaGraphEdge(
                                      toscaNodeType.Value.DerivedFrom,
                                      toscaNodeType.Key));
                }
            }

            this.action = action;
        }
Exemplo n.º 31
0
        public void GraphWithSelfEdges()
        {
            AdjacencyGraph <string, Edge <string> > g = new AdjacencyGraph <string, Edge <string> >(false);

            g.AddVertex("v1");
            g.AddEdge(new Edge <string>("v1", "v1"));

            foreach (string v in g.Vertices)
            {
                parents[v] = v;
            }

            // compute
            dfs.Compute();

            CheckDfs();
        }
Exemplo n.º 32
0
        public static AdjacencyGraph <string, TaggedEdge <string, int> > CreateGraphPart1()
        {
            var graph = new AdjacencyGraph <string, TaggedEdge <string, int> >();

            foreach (var rule in ParseInput())
            {
                string name = rule.Name;
                graph.AddVertex(name);
                foreach (var(innerName, amount) in rule.InnerBags)
                {
                    graph.AddVertex(innerName);
                    graph.AddEdge(new TaggedEdge <string, int>(innerName, name, amount));
                }
            }

            return(graph);
        }
Exemplo n.º 33
0
        public void AdjacentTest()
        {
            AdjacencyGraph g = new AdjacencyGraph();
            Vertex
                v1 = new Vertex(),
                v2 = new Vertex(),
                v3 = new Vertex();

            g.AddVertex(v1);
            g.AddVertex(v2);
            g.AddVertex(v3);
            g.AddEdge(v1, v2);

            Assert.AreEqual(true, g.Adjacent(v1, v2));
            Assert.AreEqual(false, g.Adjacent(v2, v3));
            Assert.AreEqual(false, g.Adjacent(v3, v1));
        }
        public void GraphWithSelfEdgesPUT(AdjacencyGraph g, int loopBound, bool self)
        {
            Random rnd; //new Random();
            var    choose1 = PexChoose.FromCall(this);

            rnd = choose1.ChooseValue <Random>("Random object");
            Init();
            for (int i = 0; i < loopBound; ++i)
            {
                for (int j = 0; j < i * i; ++j)
                {
                    RandomGraph.Graph(g, i, j, rnd, true);
                    Init();
                    DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g);
                    dfs.StartVertex        += new VertexHandler(this.StartVertex);
                    dfs.DiscoverVertex     += new VertexHandler(this.DiscoverVertex);
                    dfs.ExamineEdge        += new EdgeHandler(this.ExamineEdge);
                    dfs.TreeEdge           += new EdgeHandler(this.TreeEdge);
                    dfs.BackEdge           += new EdgeHandler(this.BackEdge);
                    dfs.ForwardOrCrossEdge += new EdgeHandler(this.FowardOrCrossEdge);
                    dfs.FinishVertex       += new VertexHandler(this.FinishVertex);

                    Parents.Clear();
                    DiscoverTimes.Clear();
                    FinishTimes.Clear();
                    m_Time = 0;

                    foreach (IVertex v in g.Vertices)
                    {
                        Parents[v] = v;
                    }

                    var choose = PexChoose.FromCall(this);
                    if (choose.ChooseValue <bool>("to add a self ede"))
                    {
                        IVertex selfEdge = RandomGraph.Vertex(g, rnd);
                        g.AddEdge(selfEdge, selfEdge);
                    }
                    // compute
                    dfs.Compute();

                    CheckDfs(g, dfs);
                }
            }
        }
Exemplo n.º 35
0
        public void buildGraph()
        {
            // Add some vertices to the graph
            for (int i = 0; i < fp.getXTileNum(); i++)
            {
                for (int j = 0; j < fp.getYTileNum(); j++)
                {
                    if (fp.getWalkableValue(i, j) == 0)
                    {
                        graph.AddVertex(fp.getTile(i, j).Position.X + "_" + fp.getTile(i, j).Position.Y);
                        //m_parent.PostMessage(fp.getTile(i, j).Position.X + "_" + fp.getTile(i, j).Position.Y);
                    }

                    if (fp.getTile(i, j).endPoint)
                    {
                        this.targetPoint = i + "_" + j;
                    }
                }
            }

            edges     = new List <Edge <string> >();
            neighbors = new List <FloorTile>();

            for (int i = 0; i < fp.getXTileNum(); i++)
            {
                for (int j = i; j < fp.getYTileNum(); j++)
                {
                    if (fp.getWalkableValue(i, j) == 0)
                    {
                        neighbors = fp.getTile(i, j).getNeighbours();

                        //m_parent.PostMessage(neighbors.Count);
                        for (int k = 0; k < neighbors.Count; k++)
                        {
                            Edge <string> myedge = new Edge <string>(
                                fp.getTile(i, j).Position.X + "_" + fp.getTile(i, j).Position.Y,
                                neighbors[k].Position.X + "_" + neighbors[k].Position.Y);
                            edges.Add(myedge);
                            graph.AddEdge(myedge);
                            edgeCost.Add(myedge, 7 - fp.getTile(i, j).openness(5));
                        }
                    }
                }
            }
        }
Exemplo n.º 36
0
        /// Summary
        /// Time: 8 min 17 sec
        /// Pattern: AAAA, Parameterized stub
        /// Pex Limitations - Not able to generate any test due to the following issue:
        /// <boundary> maxbranches - 40000 (maximum number of branches exceeded)
        /// [execution] Please notice: A branch in the method System.Collections.Hashtable+HashtableEnumerator.MoveNext was executed 5777 times;
        /// please check that the code is not stuck in an infinite loop.
        /// [test] (run 1) GraphWithoutSelfEdgesPUT01, pathboundsexceeded (duplicate)
        /// [execution] Please notice: A branch in the method System.Collections.Hashtable+HashtableEnumerator.MoveNext was executed 4344 times;
        /// please check that the code is not stuck in an infinite loop.
        /// [test] (run 2) GraphWithoutSelfEdgesPUT01, pathboundsexceeded (duplicate)
        /// <summary>
        /// @Author:Madhuri
        /// </summary>
        public void GraphWithSelfEdgesPUT(AdjacencyGraph g, int loopBound)
        {
            Random rnd = new Random();

            Init();
            for (int i = 0; i < loopBound; ++i)
            {
                for (int j = 0; j < i * i; ++j)
                {
                    RandomGraph.Graph(g, i, j, rnd, true);
                    BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(g);
                    bfs.InitializeVertex += new VertexHandler(this.InitializeVertex);
                    bfs.DiscoverVertex   += new VertexHandler(this.DiscoverVertex);
                    bfs.ExamineEdge      += new EdgeHandler(this.ExamineEdge);
                    bfs.ExamineVertex    += new VertexHandler(this.ExamineVertex);
                    bfs.TreeEdge         += new EdgeHandler(this.TreeEdge);
                    bfs.NonTreeEdge      += new EdgeHandler(this.NonTreeEdge);
                    bfs.GrayTarget       += new EdgeHandler(this.GrayTarget);
                    bfs.BlackTarget      += new EdgeHandler(this.BlackTarget);
                    bfs.FinishVertex     += new VertexHandler(this.FinishVertex);

                    Parents.Clear();
                    Distances.Clear();
                    m_CurrentDistance = 0;

                    m_SourceVertex = RandomGraph.Vertex(g, rnd);
                    var choose = PexChoose.FromCall(this);
                    if (choose.ChooseValue <bool>("to add a self ede"))
                    {
                        IVertex selfEdge = RandomGraph.Vertex(g, rnd);
                        g.AddEdge(selfEdge, selfEdge);
                    }
                    // g.RemoveEdge(RandomGraph.Edge(g, rnd));
                    foreach (IVertex v in g.Vertices)
                    {
                        Distances[v] = int.MaxValue;
                        Parents[v]   = v;
                    }
                    Distances[SourceVertex] = 0;
                    bfs.Compute(SourceVertex);

                    CheckBfs(g, bfs);
                }
            }
        }
 public void YenLoopCaseTest()
 {
   var graph = new AdjacencyGraph<char, TaggedEquatableEdge<char, double>>(true);
   graph.AddVertexRange("1");
   var yen = new YenShortestPathsAlgorithm<char>(graph, '1', '1', 10);
   graph.AddEdge(new TaggedEquatableEdge<char, double>('1', '1', 7));
   var exeptionWas = false;
   try
   {
     yen.Execute();
   }
   catch (Exception e)
   {
     Assert.AreEqual(true, e is NoPathFoundException);
     exeptionWas = true;
   }
   Assert.AreEqual(exeptionWas, true);
 }
Exemplo n.º 38
0
        /// <summary>
        /// Get adjacency graph from input graph
        /// </summary>
        /// <param name="graph">GraphMapData</param>
        /// <returns>AdjacencyGraph</returns>
        public static AdjacencyGraph <string, Edge <string> > GetAdjacencyGraph(GraphMapData graph)
        {
            ICollection <NodeMapData> nodes = graph.GetNodes();
            AdjacencyGraph <string, Edge <string> > adjacencyGraph = new AdjacencyGraph <string, Edge <string> >(true, nodes.Count);

            foreach (NodeMapData node in nodes)
            {
                adjacencyGraph.AddVertex(node.Id);
            }

            foreach (EdgeMapData edge in graph.GetEdges())
            {
                Edge <string> quickGraphEdge = new Edge <string>(edge.Source, edge.Target);
                adjacencyGraph.AddEdge(quickGraphEdge);
            }

            return(adjacencyGraph);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Get adjacency graph from input graph
        /// </summary>
        /// <param name="graph">GraphMapData</param>
        /// <returns>AdjacencyGraph</returns>
        public static AdjacencyGraph<string, Edge<string>> GetAdjacencyGraph(GraphMapData graph)
        {
            ICollection<NodeMapData> nodes = graph.GetNodes();
            AdjacencyGraph<string, Edge<string>> adjacencyGraph = new AdjacencyGraph<string, Edge<string>>(true, nodes.Count);

            foreach (NodeMapData node in nodes)
            {
                adjacencyGraph.AddVertex(node.Id);
            }

            foreach (EdgeMapData edge in graph.GetEdges())
            {
                Edge<string> quickGraphEdge = new Edge<string>(edge.Source, edge.Target);
                adjacencyGraph.AddEdge(quickGraphEdge);
            }

            return adjacencyGraph;
        }
Exemplo n.º 40
0
        public static IEnumerable <Edge <GraphVertex> > ShortestWayAstarAlgorithm(List <GraphVertex> listVertex, List <GraphEdge> listEdge, GraphVertex start, GraphVertex end)
        {
            AdjacencyGraph <GraphVertex, Edge <GraphVertex> > graph = new AdjacencyGraph <GraphVertex, Edge <GraphVertex> >();

            foreach (var vert in listVertex)
            {
                graph.AddVertex(vert);
            }
            foreach (var edge in listEdge)
            {
                graph.AddEdge(new Edge <GraphVertex>(edge.StartVertex, edge.EndVertex));
            }
            Dictionary <Edge <GraphVertex>, double> edgeCost = new Dictionary <Edge <GraphVertex>, double>();
            int i = 0;

            foreach (var edge in graph.Edges)
            {
                double eCost = EdgeCostSearching(edge.Source, edge.Target, listEdge);
                edgeCost.Add(edge, eCost);
                i++;
            }


            Func <Edge <GraphVertex>, double> getW = edge => edgeCost[edge];

            //---------------------------------
            IEnumerable <Edge <GraphVertex> > edgessAstar;
            AStarShortestPathAlgorithm <GraphVertex, Edge <GraphVertex> >     astar    = new AStarShortestPathAlgorithm <GraphVertex, Edge <GraphVertex> >(graph, getW, x => 0.0);
            VertexDistanceRecorderObserver <GraphVertex, Edge <GraphVertex> > distObsA = new VertexDistanceRecorderObserver <GraphVertex, Edge <GraphVertex> >(getW);

            using (distObsA.Attach(astar))
            {
                VertexPredecessorRecorderObserver <GraphVertex, Edge <GraphVertex> > predObs = new VertexPredecessorRecorderObserver <GraphVertex, Edge <GraphVertex> >();
                using (predObs.Attach(astar))
                {
                    astar.Compute(start);
                    if (predObs.TryGetPath(end, out edgessAstar))
                    {
                        return(edgessAstar);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 41
0
        public static void ParseFile(AdjacencyGraph <String, SEdge <String> > graph, string inputFile)
        {
            var    reader = new StreamReader(File.OpenRead(inputFile));
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (!string.IsNullOrWhiteSpace(line))
                {
                    var nodes      = line.Split(new char[] { '>', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    var firstNode  = nodes[0];
                    var secondNode = nodes[1];
                    graph.AddVertex(firstNode);
                    graph.AddVertex(secondNode);
                    graph.AddEdge(new SEdge <string>(firstNode, secondNode));
                }
            }
        }
Exemplo n.º 42
0
        public void DumpVariablesToDot(string fileName)
        {
            var graph = new AdjacencyGraph <SecondaryEntity, TaggedEdge <SecondaryEntity, string> >();

            var allVariables =
                CollectAllMethods()
                .SelectMany(method => method.Variables.Values.Union(method.AdditionalVariables.Cast <SecondaryEntity>()))
                .Concat(myClasses.Values
                        .SelectMany(clazz => clazz.Fields)
                        .Cast <SecondaryEntity>())
                .ToList();

            foreach (var variable in allVariables)
            {
                graph.AddVertex(variable);
            }

            foreach (var variable in allVariables)
            {
                foreach (var(recipient, top) in variable.AllRecipients)
                {
                    var edge = new TaggedEdge <SecondaryEntity, string>(variable, recipient, top ? "t" : "b");
                    graph.AddEdge(edge);
                }
            }

            var algorithm = new GraphvizAlgorithm <SecondaryEntity, TaggedEdge <SecondaryEntity, string> >(graph);

            algorithm.FormatVertex += (sender, args) =>
                                      args.VertexFormatter.Label = String.Concat(
                args.Vertex.CollectedPrimaries
                .Select(reference => reference as ResolvedClassId)
                .Where(entity => entity != null)
                .Select(entity => entity.GlobalId.ToString() + " "));

            algorithm.FormatEdge += (sender, args) =>
            {
                args.EdgeFormatter.Label.Value = "";
                args.EdgeFormatter.StrokeColor = args.Edge.Tag == "t" ? Color.Red : Color.Blue;
            };

            algorithm.Generate(new FileDotEngine(), fileName);
        }
Exemplo n.º 43
0
        public Feature(IGridShape shape)
        {
            Shape      = shape;
            FieldGraph = new AdjacencyGraph <SquareMapField, Edge <SquareMapField> >();
            foreach (var coords in Shape.Interior)
            {
                var field = new SquareMapField(coords, this);
                _fields[coords] = field;
                FieldGraph.AddVertex(field);
            }

            foreach (var field in _fields.Values)
            {
                foreach (var adjacentField in FindAdjacentFields(field.Coordinates))
                {
                    FieldGraph.AddEdge(new Edge <SquareMapField>(field, adjacentField));
                }
            }
        }
Exemplo n.º 44
0
        private void addEdges()
        {
            char[] delimit1 = { '\n' };
            char[] delimit2 = { ',', ' ', '.' };

            string[] arraySplit1 = isiFileTextBox.Text.ToString().Split(delimit1);
            for (int i = 0; i < arraySplit1.Length; i++)
            {
                string[] arraySplit2 = arraySplit1[i].Split(delimit2);
                for (int j = 1; j < arraySplit2.Length; j++)
                {
                    if (!String.IsNullOrEmpty(arraySplit2[j]) && !String.IsNullOrWhiteSpace(arraySplit2[j]))
                    {
                        Edge <string> edge = new Edge <string>(arraySplit2[j], arraySplit2[0]);
                        graph.AddEdge(edge);
                    }
                }
            }
        }
Exemplo n.º 45
0
        static AdjacencyGraph <string, Edge <string> > MakeGraph(Dictionary <string, User> users)
        {
            AdjacencyGraph <string, Edge <string> > graph = new AdjacencyGraph <string, Edge <string> >(true);

            foreach (var user in users)
            {
                graph.AddVertex(user.Key);
            }

            foreach (var user in users)
            {
                foreach (var friend in user.Value.friends.Keys)
                {
                    graph.AddEdge(new Edge <string>(user.Key, friend.name));
                }
            }

            return(graph);
        }
Exemplo n.º 46
0
        /// <summary>
        ///	Sort the specified resources in dependency order (most-dependent-first).
        /// </summary>
        /// <param name="resources">The resources to examine.</param>
        /// <returns>
        ///	A read-only list of <see cref="Resource"/>s in dependency order.
        /// </returns>
        public static IReadOnlyList <Resource> DependencySort(IReadOnlyCollection <Resource> resources)
        {
            if (resources == null)
            {
                throw new ArgumentNullException(nameof(resources));
            }

            try
            {
                Dictionary <string, Resource> resourcesById = resources.ToDictionary(resource => resource.ResourceId);

                AdjacencyGraph <Resource, Edge <Resource> > resourceDependencies = new AdjacencyGraph <Resource, Edge <Resource> >();

                foreach (string resourceId in resourcesById.Keys)
                {
                    Resource resource = resourcesById[resourceId];
                    if (!resourceDependencies.AddVertex(resource))
                    {
                        continue; // Already processed.
                    }
                    if (resource.DependsOn != null)
                    {
                        foreach (string dependsOnResourceId in resource.DependsOn)
                        {
                            Resource dependsOnResource;
                            if (!resourcesById.TryGetValue(dependsOnResourceId, out dependsOnResource))
                            {
                                throw new TemplateParserException($"Resource '{resourceId}' depends on non-existent resource '{dependsOnResourceId}'.");
                            }

                            resourceDependencies.AddEdge(new Edge <Resource>(resource, dependsOnResource));
                        }
                    }
                }

                return(resourceDependencies.TopologicalSort().ToList());
            }
            catch (NonAcyclicGraphException ex)
            {
                throw new TemplateParserException("The template contains a circular dependency.", ex);
            }
        }
Exemplo n.º 47
0
        public void AddOneEdge()
        {
            AdjacencyGraph g    = new AdjacencyGraph();
            IVertex        v    = g.AddVertex();
            IVertex        u    = g.AddVertex();
            IEdge          edge = g.AddEdge(u, v);

            this.target = new ReversedEdgeAugmentorAlgorithm(g);
            target.AddReversedEdges();

            Assert.AreEqual(2, this.target.VisitedGraph.VerticesCount);
            Assert.AreEqual(2, this.target.VisitedGraph.EdgesCount);
            CollectionAssert.AreCountEqual(1, this.target.AugmentedEdges);
            VerifyReversedEdges();

            IEdge reversedEdge = this.target.ReversedEdges[edge];

            Assert.IsNotNull(reversedEdge);
            Assert.IsTrue(this.target.AugmentedEdges.Contains(reversedEdge));
        }
Exemplo n.º 48
0
        private void addEdgesToGraph(AdjacencyGraph <string, Edge <string> > graph, Dictionary <Edge <string>, double> edgeCost)
        {
            var possibleEdges = new List <Edge <string> >();

            for (var vertex1 = 0; vertex1 < _vertexes - 1; ++vertex1)
            {
                for (var vertex2 = vertex1 + 1; vertex2 < _vertexes; ++vertex2)
                {
                    possibleEdges.Add(new Edge <string>(vertex1.ToString(), vertex2.ToString()));
                }
            }
            foreach (var _ in Range(0, _edges))
            {
                var edgeIndex = _rand.Next(0, possibleEdges.Count);
                var edge      = possibleEdges[edgeIndex];
                possibleEdges.RemoveAt(edgeIndex);
                graph.AddEdge(edge);
                edgeCost.Add(edge, _rand.NextDouble(1, 100));
            }
        }
Exemplo n.º 49
0
        public Graph CreateGraph(RulesEngine engine)
        {
            var visitor = new GraphRulesEngineVisitor();
            engine.Visit(visitor);

            var graph = new AdjacencyGraph<Vertex, Edge<Vertex>>();

            visitor.Vertices.Each(x => graph.AddVertex(x));
            visitor.Edges.Each(x => graph.AddEdge(new Edge<Vertex>(x.From, x.To)));

            GleeGraphPopulator<Vertex, Edge<Vertex>> glee = graph.CreateGleePopulator();

            glee.NodeAdded += NodeStyler;
            glee.EdgeAdded += EdgeStyler;
            glee.Compute();

            Graph gleeGraph = glee.GleeGraph;

            return gleeGraph;
        }
Exemplo n.º 50
0
        /// <summary>
        ///	Sort the specified resources in dependency order (most-dependent-first).
        /// </summary>
        /// <param name="resources">The resources to examine.</param>
        /// <returns>
        ///	A read-only list of <see cref="Resource"/>s in dependency order.
        /// </returns>
        public static IReadOnlyList<Resource> DependencySort(IReadOnlyCollection<Resource> resources)
        {
            if (resources == null)
            {
                throw new ArgumentNullException(nameof(resources));
            }

            try
            {
                Dictionary<string, Resource> resourcesById = resources.ToDictionary(resource => resource.ResourceId);

                AdjacencyGraph<Resource, Edge<Resource>> resourceDependencies = new AdjacencyGraph<Resource, Edge<Resource>>();

                foreach (string resourceId in resourcesById.Keys)
                {
                    Resource resource = resourcesById[resourceId];
                    if (!resourceDependencies.AddVertex(resource))
                        continue; // Already processed.

                    if (resource.DependsOn != null)
                    {
                        foreach (string dependsOnResourceId in resource.DependsOn)
                        {
                            Resource dependsOnResource;
                            if (!resourcesById.TryGetValue(dependsOnResourceId, out dependsOnResource))
                            {
                                throw new TemplateParserException($"Resource '{resourceId}' depends on non-existent resource '{dependsOnResourceId}'.");
                            }

                            resourceDependencies.AddEdge(new Edge<Resource>(resource, dependsOnResource));
                        }
                    }
                }

                return resourceDependencies.TopologicalSort().ToList();
            }
            catch (NonAcyclicGraphException ex)
            {
                throw new TemplateParserException("The template contains a circular dependency.", ex);
            }
        }
Exemplo n.º 51
0
        static AdjacencyGraph<int, Edge<int>> ReadGraph(string filePath)
        {
            var graph = new AdjacencyGraph<int, Edge<int>>();

            foreach (string vertexAndEdges in File.ReadAllLines(filePath))
            {
                List<string> nums = vertexAndEdges.Split(' ').ToList();

                graph.AddVertex(Convert.ToInt32(nums[0]));

                for (int i = 1; i <= nums.Count - 1; i++)
                {
                    if (nums[i] != null && nums[i] != String.Empty)
                    {
                        Edge<int> edge = new Edge<int>(Convert.ToInt32(nums[0]), Convert.ToInt32(nums[i]));
                        graph.AddEdge(edge);
                    }
                }
            }
            return graph;
        }
Exemplo n.º 52
0
        public void YenLoopCaseTest()
        {
            var graph = new AdjacencyGraph <char, TaggedEquatableEdge <char, double> >(true);

            graph.AddVertexRange("1");
            var yen = new YenShortestPathsAlgorithm <char>(graph, '1', '1', 10);

            graph.AddEdge(new TaggedEquatableEdge <char, double>('1', '1', 7));
            var exeptionWas = false;

            try
            {
                yen.Execute();
            }
            catch (Exception e)
            {
                Assert.AreEqual(true, e is NoPathFoundException);
                exeptionWas = true;
            }
            Assert.AreEqual(exeptionWas, true);
        }
        public void DijkstraSimpleGraph2()
        {
            var graph     = new AdjacencyGraph <char, Edge <char> >();
            var distances = new Dictionary <Edge <char>, double>();

            graph.AddVertexRange("ABCDE");
            AddEdge('A', 'C', 1);
            AddEdge('B', 'B', 2);
            AddEdge('B', 'D', 1);
            AddEdge('B', 'E', 2);
            AddEdge('C', 'B', 7);
            AddEdge('C', 'D', 3);
            AddEdge('D', 'E', 1);
            AddEdge('E', 'A', 1);
            AddEdge('E', 'B', 1);

            var algorithm    = new DijkstraShortestPathAlgorithm <char, Edge <char> >(graph, AlgorithmExtensions.GetIndexer(distances));
            var predecessors = new VertexPredecessorRecorderObserver <char, Edge <char> >();

            using (predecessors.Attach(algorithm))
                algorithm.Compute('A');

            Assert.AreEqual(0, algorithm.Distances['A']);
            Assert.AreEqual(6, algorithm.Distances['B']);
            Assert.AreEqual(1, algorithm.Distances['C']);
            Assert.AreEqual(4, algorithm.Distances['D']);
            Assert.AreEqual(5, algorithm.Distances['E']);

            #region Local function

            void AddEdge(char source, char target, double weight)
            {
                var edge = new Edge <char>(source, target);

                distances[edge] = weight;
                graph.AddEdge(edge);
            }

            #endregion
        }
        private static void ProcessIssue(AdjacencyGraph <ExternalIssueDetails, SubIssueEdge> graph, ExternalIssueDetails contextIssue, ExternalIssueDetails parentIssue = null)
        {
            if (parentIssue != null)
            {
                var parent = parentIssue;
                if (graph.ContainsVertex(parentIssue))
                {
                    parent = graph.Vertices.First(e => e.Equals(parentIssue));
                }

                graph.AddVertex(contextIssue);
                graph.AddEdge(new SubIssueEdge(parent, contextIssue, "SubIssue"));
            }

            if (contextIssue.SubIssues != null)
            {
                foreach (var issue in contextIssue.SubIssues)
                {
                    ProcessIssue(graph, issue, contextIssue);
                }
            }
        }
Exemplo n.º 55
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="computer">
        /// A function that computes the weight
        /// of any <see cref="ILineString">edge</see> of the graph
        /// </param>
        /// <returns></returns>
        public DijkstraShortestPathAlgorithm <IPoint, IEdge <IPoint> > PrepareAlgorithm(ComputeWeightDelegate computer)
        {
            if (strings.Count < 2)
            {
                throw new TopologyException("you must specify two or more geometries to build a graph");
            }

            IMultiLineString edges = BuildEdges();

            Dictionary <IEdge <IPoint>, double>      consts = new Dictionary <IEdge <IPoint>, double>(edges.NumGeometries);
            AdjacencyGraph <IPoint, IEdge <IPoint> > graph  = new AdjacencyGraph <IPoint, IEdge <IPoint> >(true);

            foreach (ILineString str in edges.Geometries)
            {
                IPoint vertex1 = str.StartPoint;
                Assert.IsTrue(vertex1 != null);
                if (!graph.ContainsVertex(vertex1))
                {
                    graph.AddVertex(vertex1);
                }

                IPoint vertex2 = str.EndPoint;
                Assert.IsTrue(vertex2 != null);
                if (!graph.ContainsVertex(vertex2))
                {
                    graph.AddVertex(vertex2);
                }

                double        weight = computer(str);
                Edge <IPoint> edge   = new Edge <IPoint>(vertex1, vertex2);
                Assert.IsTrue(edge != null);

                graph.AddEdge(edge);
                consts.Add(edge, weight);
            }

            // Use Dijkstra
            return(new DijkstraShortestPathAlgorithm <IPoint, IEdge <IPoint> >(graph, consts));
        }
Exemplo n.º 56
0
        public static AdjacencyGraph <ProgramNode, Edge <ProgramNode> > GetAdjacencyGraph()
        {
            Regex nodeAndWeightRegex = new Regex(@"([a-z]+)\(([0-9]+)\)");
            Regex allEdgesRegex      = new Regex(@"->(.*)");
            Regex nodeRegex          = new Regex(@"([a-z]+)");
            var   adjacencyGraph     = new AdjacencyGraph <ProgramNode, Edge <ProgramNode> >();

            foreach (string nodesString in input)
            {
                var         nodeMatches = nodeAndWeightRegex.Matches(nodesString.Replace(" ", ""));
                string      name        = nodeMatches[0].Groups[1].Value;
                int         weight      = int.Parse(nodeMatches[0].Groups[2].Value);
                ProgramNode parentNode  = new ProgramNode(name, weight);
                adjacencyGraph.AddVertex(parentNode);
            }

            foreach (string nodesString in input)
            {
                var         nodeMatches = nodeAndWeightRegex.Matches(nodesString.Replace(" ", ""));
                string      name        = nodeMatches[0].Groups[1].Value;
                int         weight      = int.Parse(nodeMatches[0].Groups[2].Value);
                ProgramNode parentNode  = adjacencyGraph.Vertices.FirstOrDefault(pn => pn.Name == name);

                var edgeMatches = allEdgesRegex.Matches(nodesString.Replace(" ", ""));
                if (edgeMatches.Count == 0)
                {
                    continue;
                }
                var edgeNameMatches = nodeRegex.Matches(edgeMatches[0].Value);
                foreach (Match match in edgeNameMatches)
                {
                    ProgramNode childNode = adjacencyGraph.Vertices.FirstOrDefault(pn => pn.Name == match.Value);
                    adjacencyGraph.AddEdge(new Edge <ProgramNode>(parentNode, childNode));
                }
            }

            return(adjacencyGraph);
        }
Exemplo n.º 57
0
        protected internal AdjacencyGraph <ProjectTargetInstance, Edge <ProjectTargetInstance> > BuildTargetGraph(Project project)
        {
            AdjacencyGraph <ProjectTargetInstance, Edge <ProjectTargetInstance> > graph =
                new AdjacencyGraph <ProjectTargetInstance, Edge <ProjectTargetInstance> >();

            foreach (string key in project.Targets.Keys)
            {
                var target = project.Targets[key];
                if (!graph.ContainsVertex(target))
                {
                    graph.AddVertex(target);
                }

                // TODO: DependsOnTargets needs to be evalueated
                string depTargetsString = target.DependsOnTargets != null ? target.DependsOnTargets : string.Empty;

                List <string> dependentTargets = target.GetDependsOnTargetsAsList(project).ToList();

                string depTargetsStringEvaluated = project.ExpandString(depTargetsString);

                dependentTargets.ToList().ForEach(depTarget => {
                    var dt = project.Targets[depTarget];
                    if (dt != null)
                    {
                        if (!graph.ContainsVertex(dt))
                        {
                            graph.AddVertex(dt);
                        }

                        Edge <ProjectTargetInstance> e = new Edge <ProjectTargetInstance>(target, dt);
                        graph.AddEdge(e);
                    }
                });
            }

            return(graph);
        }
        private void CreateGraph()
        {
            _graph.Clear();
            _projects.Clear();

            for (int i = 0; i < _solution.Projects.Count; i++)
            {
                var project = _solution.Projects[i];
                _projects[project] = i;

                if (project.IsSelected)
                {
                    _graph.AddVertex(i);
                }
            }

            foreach (var project in _solution.Projects)
            {
                if (project.IsSelected == false)
                {
                    continue;
                }

                int currentProject = _projects[project];

                foreach (var projectRef in project.ProjectReferences)
                {
                    if (_solution.GetProject(projectRef).IsSelected == false)
                    {
                        continue;
                    }

                    int toVertex = _projects[_solution.GetProject(projectRef)];
                    _graph.AddEdge(new Edge <int>(currentProject, toVertex));
                }
            }
        }
        public void CheckPredecessorLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            Edge<int> e12 = new Edge<int>(1, 2); g.AddEdge(e12);
            Edge<int> e23 = new Edge<int>(2, 3); g.AddEdge(e23);

            Dictionary<Edge<int>, double> weights =
                DijkstraShortestPathAlgorithm<int, Edge<int>>.UnaryWeightsFromEdgeList(g);
            DijkstraShortestPathAlgorithm<int, Edge<int>> dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, weights);
            VertexPredecessorRecorderObserver<int, Edge<int>> vis = new VertexPredecessorRecorderObserver<int, Edge<int>>();
            vis.Attach(dij);
            dij.Compute(1);

            IList<Edge<int>> col = vis.Path(2);
            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(e12, col[0]);

            col = vis.Path(3);
            Assert.AreEqual(2, col.Count);
            Assert.AreEqual(e12, col[0]);
            Assert.AreEqual(e23, col[1]);
        }
 private static void AddEdge(
     AdjacencyGraph<char, Edge<char>> g, 
     Dictionary<Edge<char>, double> distances,
     char source, char target, double weight)
 {
     var ac = new Edge<char>(source, target); distances[ac] = weight; g.AddEdge(ac);
 }