public void SimpleGraph() { var graph = new BidirectionalGraph <string, Edge <string> >(); const int nbVertices = 3; var vertices = new string[nbVertices]; for (int i = 1; i <= nbVertices; ++i) { vertices[i - 1] = i.ToString(); graph.AddVertex(i.ToString()); } graph.AddEdge(new Edge <string>(vertices[0], vertices[1])); graph.AddEdge(new Edge <string>(vertices[1], vertices[2])); var algorithm = new LayeredTopologicalSortAlgorithm <string, Edge <string> >(graph); int layerFinished = 0; var verticesPerLayer = new[] { new[] { vertices[0] }, new[] { vertices[1] }, new[] { vertices[2] } }; var verticesPerLayerStack = new Stack <string[]>(verticesPerLayer.Reverse()); algorithm.LayerFinished += (sender, args) => { Assert.AreEqual(layerFinished, args.LayerIndex); CollectionAssert.AreEquivalent(verticesPerLayerStack.Pop(), args.Vertices); ++layerFinished; }; algorithm.Compute(); Assert.AreEqual(3, layerFinished); CheckAlgorithmResults(algorithm, verticesPerLayer); }
public void CloneTest() { var g = new BidirectionalGraph<int, Edge<int>>(); g.AddVertexRange(new int[3] {1, 2, 3}); g.AddEdge(new Edge<int>(1, 2)); g.AddEdge(new Edge<int>(2, 3)); g.AddEdge(new Edge<int>(3, 1)); Assert.AreEqual(3, g.VertexCount); Assert.AreEqual(3, g.EdgeCount); var h = g.Clone(); Assert.AreEqual(3, h.VertexCount); Assert.AreEqual(3, h.EdgeCount); h.AddVertexRange(new int[4] { 10, 11, 12, 13 }); h.AddEdge(new Edge<int>(10, 11)); Assert.AreEqual(7, h.VertexCount); Assert.AreEqual(4, h.EdgeCount); var i = 0; foreach (var e in h.Edges) i++; Assert.AreEqual(4, i); Assert.AreEqual(3, g.VertexCount); Assert.AreEqual(3, g.EdgeCount); }
private void AddVertex_Click(object sender, RoutedEventArgs e) { if (graph == null || graph.VertexCount >= 100) { return; } var rnd = new Random(DateTime.Now.Millisecond); int verticesToAdd = Math.Max(graph.VertexCount / 4, 1); var parents = new string[verticesToAdd]; for (int j = 0; j < verticesToAdd; j++) { parents[j] = graph.Vertices.ElementAt(rnd.Next(graph.VertexCount)); } for (int i = 0; i < verticesToAdd; i++) { string newVertex = string.Empty; do { newVertex = rnd.Next(0, graph.VertexCount + 20) + "_new"; } while (graph.ContainsVertex(newVertex)); graph.AddVertex(newVertex); if (graph.VertexCount < 2) { return; } //string vo1 = graph.Vertices.ElementAt(rnd.Next(Math.Max(9 * graph.VertexCount / 10, graph.VertexCount - 1))); graph.AddEdge(new Edge <string>(parents[i], newVertex)); } }
private IBidirectionalGraph <Node, IEdge <Node> > CreateGraph(Node root) { var graph = new BidirectionalGraph <Node, IEdge <Node> >(); var nodes = new Queue <Node>(); graph.AddVertex(root); nodes.Enqueue(root); while (nodes.Count > 0) { var node = nodes.Dequeue(); if (node.left != null) { var edge = new WeightedEdge <Node>(node, node.left, 0); graph.AddVertex(node.left); graph.AddEdge(edge); nodes.Enqueue(node.left); } if (node.right != null) { var edge = new WeightedEdge <Node>(node, node.right, 1); graph.AddVertex(node.right); graph.AddEdge(edge); nodes.Enqueue(node.right); } } return(graph); }
// Original Source: https://www.youtube.com/watch?v=VTbuvkaPGxE private void RefreshGraph() { while (_graphToVisualize.Edges.Count() > 0) { _graphToVisualize.RemoveEdge(_graphToVisualize.Edges.First()); } _graphToVisualize.AddVertex("SinglyLinkedList"); _graphToVisualize.AddVertex("null"); foreach (SinglyLinkedListNode <string> node in SinglyLinkedListNode <string> .allNodes) { _graphToVisualize.AddVertex(node.ToString()); } foreach (SinglyLinkedListNode <string> node in SinglyLinkedListNode <string> .allNodes) { if (node.Next == null) { _graphToVisualize.AddEdge(new Edge <object>(node.ToString(), "null")); } else { _graphToVisualize.AddEdge(new Edge <object>(node.ToString(), node.Next.ToString())); } } try { _graphToVisualize.AddEdge(new Edge <object>("SinglyLinkedList", linkedList.First() ?? "null")); } catch (NotImplementedException) { _graphToVisualize.AddEdge(new Edge <object>("SinglyLinkedList", "null")); } }
public void TwoPathTest() { /* * A-B-C-D * E F * G-H-I-J */ var graph = new BidirectionalGraph <string, SimpleWeightedEdge>(); graph.AddNodes("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"); graph.AddEdge("A", "B", new SimpleWeightedEdge(1)); graph.AddEdge("B", "C", new SimpleWeightedEdge(1)); graph.AddEdge("C", "D", new SimpleWeightedEdge(1)); graph.AddEdge("A", "E", new SimpleWeightedEdge(1)); graph.AddEdge("E", "G", new SimpleWeightedEdge(1)); graph.AddEdge("D", "F", new SimpleWeightedEdge(1)); graph.AddEdge("F", "J", new SimpleWeightedEdge(1)); graph.AddEdge("G", "H", new SimpleWeightedEdge(1)); graph.AddEdge("H", "I", new SimpleWeightedEdge(1)); graph.AddEdge("J", "I", new SimpleWeightedEdge(1)); var algorithm = new AStar <string, SimpleWeightedEdge>(graph, (u, v) => 1); var result = algorithm.Compute("B", "H").ToList(); Assert.AreEqual(5, result.Count); Assert.AreEqual("B", result[0]); Assert.AreEqual("A", result[1]); Assert.AreEqual("E", result[2]); Assert.AreEqual("G", result[3]); Assert.AreEqual("H", result[4]); }
public void Repro13160() { // create a new graph var graph = new BidirectionalGraph<int, SEquatableEdge<int>>(false); // adding vertices for (int i = 0; i < 3; ++i) for(int j = 0;j<3;++j) graph.AddVertex(i * 3 + j); // adding Width edges for (int i = 0; i < 3; ++i) for(int j = 0; j < 2;++j) graph.AddEdge(new SEquatableEdge<int>(i * 3 +j, i * 3 + j + 1)); // adding Length edges for (int i = 0; i < 2; ++i) for(int j = 0; j < 3;++j) graph.AddEdge(new SEquatableEdge<int>(i * 3 + j, (i+1) * 3 + j)); // create cross edges foreach (var e in graph.Edges) graph.AddEdge(new SEquatableEdge<int>(e.Target, e.Source)); // breaking graph apart for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (i == 1) graph.RemoveVertex(i * 3 + j); var target = new CyclePoppingRandomTreeAlgorithm<int, SEquatableEdge<int>>(graph); target.Compute(2); foreach(var kv in target.Successors) Console.WriteLine("{0}: {1}", kv.Key, kv.Value); }
public void Clone() { var graph = new BidirectionalGraph <int, Edge <int> >(); graph.AddVertexRange(new[] { 1, 2, 3 }); graph.AddEdge(new Edge <int>(1, 2)); graph.AddEdge(new Edge <int>(2, 3)); graph.AddEdge(new Edge <int>(3, 1)); Assert.AreEqual(3, graph.VertexCount); Assert.AreEqual(3, graph.EdgeCount); var clonedGraph = graph.Clone(); Assert.AreEqual(3, clonedGraph.VertexCount); Assert.AreEqual(3, clonedGraph.EdgeCount); clonedGraph.AddVertexRange(new[] { 10, 11, 12, 13 }); clonedGraph.AddEdge(new Edge <int>(10, 11)); Assert.AreEqual(7, clonedGraph.VertexCount); Assert.AreEqual(4, clonedGraph.EdgeCount); int edgeCount = clonedGraph.Edges.Count(); Assert.AreEqual(4, edgeCount); Assert.AreEqual(3, graph.VertexCount); Assert.AreEqual(3, graph.EdgeCount); }
public static IBidirectionalGraph <object, IEdge <object> > AdjacentyMatrixToGraph(MatrixWithHeaders matrixWithHeaders) { var graph = new BidirectionalGraph <object, IEdge <object> >(); var headers = matrixWithHeaders.Headers; var matrix = matrixWithHeaders.Matrix; foreach (var item in headers) { graph.AddVertex(item.Value); } if (headers.Count > 1) { for (int y = 0; y < matrix.GetLength(1); y++) { for (int x = 0; x < matrix.GetLength(0); x++) { if (matrix[x, y] == 1) { graph.AddEdge(new Edge <object>(headers[x], headers[y])); } } } } else { graph.AddEdge(new Edge <object>(headers[0], headers[0])); } return(graph); }
private void AddPortalsForLevel(BidirectionalGraph <Point, Edge <Point> > graph, HashSet <Portal> portals, int level) { foreach (var portalPair in portals.GroupBy(p => p.Name).Where(g => g.Count() == 2)) { var pair = portalPair.ToArray(); var outerPortal = portalPair.First(p => p.IsOuter); var innerPortal = portalPair.First(p => !p.IsOuter); // Connect the inner portal to the next level and the outer portal to to previous level. // Connect the inner portal at the level above this level to the outer portal at this level. var innerPortalSource = GetPointForLevel(innerPortal.MapLocation, level - 1); var innerPortalTarget = GetPointForLevel(outerPortal.MapLocation, level); if (graph.ContainsVertex(innerPortalSource) && graph.ContainsVertex(innerPortalTarget)) { var edge = new Edge <Point>(innerPortalSource, innerPortalTarget); graph.AddEdge(edge); graph.AddEdge(edge.Reverse); } // Connect the outer portal at this level to the inner portal at the level below this. var outerPortalSource = GetPointForLevel(outerPortal.MapLocation, level); var outerPortalTarget = GetPointForLevel(innerPortal.MapLocation, level + 1); if (graph.ContainsVertex(outerPortalSource) && graph.ContainsVertex(outerPortalTarget)) { var edge = new Edge <Point>(outerPortalSource, outerPortalTarget); graph.AddEdge(edge); graph.AddEdge(edge.Reverse); } } }
protected override void Act() { var graph = new BidirectionalGraph <string, IEdge <string> >(); /* * (A) --> (B) --> (C1) --> (D1) * \ * --> (C2) --> (D2) */ graph.AddVertex("A"); graph.AddVertex("B"); graph.AddVertex("C1"); graph.AddVertex("D1"); graph.AddVertex("C2"); graph.AddVertex("D2"); graph.AddEdge(new Edge <string>("A", "B")); graph.AddEdge(new Edge <string>("B", "C1")); graph.AddEdge(new Edge <string>("C1", "D1")); graph.AddEdge(new Edge <string>("B", "C2")); graph.AddEdge(new Edge <string>("C2", "D2")); graph.ValidateGraph(); }
private BidirectionalGraph <Point, Edge <Point> > BuildGraph(HashSet <Point> map, char[] keys, Dictionary <Point, char> doors, Point startingLocation) { var graph = new BidirectionalGraph <Point, Edge <Point> >(); graph.AddVertex(startingLocation); var pointsToCheck = new Queue <Point>(); pointsToCheck.Enqueue(startingLocation); while (pointsToCheck.Count > 0) { var source = pointsToCheck.Dequeue(); foreach (var dir in _allDirections) { // Is there a location on the map in this direction? var target = source.GetPoint(dir); if (map.Contains(target) && !graph.ContainsVertex(target)) { // Valid point that we can move to. graph.AddVertex(target); graph.AddEdge(new Edge <Point>(source, target)); graph.AddEdge(new Edge <Point>(target, source)); // Can we continue past this location? if (!doors.ContainsKey(target) || keys.Contains(doors[target])) { pointsToCheck.Enqueue(target); } } } } return(graph); }
public void NonAcyclic() { var g = new BidirectionalGraph<string, Edge<string>>( ); var vs = new string[ 4 ]; for ( int i = 1; i < 5; i++ ) { vs[ i - 1 ] = i.ToString( ); g.AddVertex( i.ToString( ) ); } g.AddEdge( new Edge<string>( vs[ 0 ], vs[ 1 ] ) ); g.AddEdge( new Edge<string>( vs[ 1 ], vs[ 2 ] ) ); g.AddEdge( new Edge<string>( vs[ 2 ], vs[ 0 ] ) ); g.AddEdge( new Edge<string>( vs[ 3 ], vs[ 0 ] ) ); try { var lts = new LayeredTopologicalSortAlgorithm<string, Edge<string>>( g ); lts.Compute( ); Assert.Fail( "It does not throw exception for non acyclic graphs." ); } catch ( NonAcyclicGraphException ex ) { Debug.WriteLine( ex.Message ); } }
public static IBidirectionalGraph <Cluster <T>, ClusterEdge <T> > ToRootedTree <T>(this IUndirectedGraph <Cluster <T>, ClusterEdge <T> > tree) { ClusterEdge <T> midpointEdge; double pointOnEdge; Cluster <T> firstCluster; GetMidpoint(tree, out midpointEdge, out pointOnEdge, out firstCluster); var rootedTree = new BidirectionalGraph <Cluster <T>, ClusterEdge <T> >(false); if (pointOnEdge < double.Epsilon) { rootedTree.AddVertex(firstCluster); GenerateRootedTree(tree, null, firstCluster, rootedTree); } else { var root = new Cluster <T>(); rootedTree.AddVertex(root); Cluster <T> otherCluster = midpointEdge.GetOtherVertex(firstCluster); rootedTree.AddVertex(otherCluster); rootedTree.AddEdge(new ClusterEdge <T>(root, otherCluster, midpointEdge.Length - pointOnEdge)); GenerateRootedTree(tree, firstCluster, otherCluster, rootedTree); rootedTree.AddVertex(firstCluster); rootedTree.AddEdge(new ClusterEdge <T>(root, firstCluster, pointOnEdge)); GenerateRootedTree(tree, otherCluster, firstCluster, rootedTree); } return(rootedTree); }
public static IBidirectionalGraph<object, IEdge<object>> AdjacentyMatrixToGraph(MatrixWithHeaders matrixWithHeaders) { var graph = new BidirectionalGraph<object, IEdge<object>>(); var headers = matrixWithHeaders.Headers; var matrix = matrixWithHeaders.Matrix; foreach (var item in headers) { graph.AddVertex(item.Value); } if (headers.Count > 1) { for (int y = 0; y < matrix.GetLength(1); y++) { for (int x = 0; x < matrix.GetLength(0); x++) { if (matrix[x, y] == 1) { graph.AddEdge(new Edge<object>(headers[x], headers[y])); } } } } else { graph.AddEdge(new Edge<object>(headers[0], headers[0])); } return graph; }
private void CreateGraphToVisualize() { segment[] graph = GetGraph("input.txt"); BidirectionalGraph <object, IEdge <object> > g = new BidirectionalGraph <object, IEdge <object> >(); for (int i = 0; i < graph.Length; i++) { g.AddVertex(i); } for (int i = 0; i < graph.Length; i++) { int ans; for (int j = i + 1; j < graph.Length; j++) { if (TryToCompare(graph[i], graph[j], out ans)) { if (ans > 0) { g.AddEdge(new Edge <object>(j, i)); } if (ans < 0) { g.AddEdge(new Edge <object>(i, j)); } else { g.AddEdge(new Edge <object>(i, j)); } g.AddEdge(new Edge <object>(j, i)); } } } GraphToVisualize = g; }
private void GenerateSpanningTree() { _spanningTree = new BidirectionalGraph <TVertex, Edge <TVertex> >(false); _spanningTree.AddVertexRange(VisitedGraph.Vertices); IQueue <TVertex> vb = new QuikGraph.Collections.Queue <TVertex>(); vb.Enqueue(VisitedGraph.Vertices.OrderBy(v => VisitedGraph.InDegree(v)).First()); switch (Parameters.SpanningTreeGeneration) { case SpanningTreeGeneration.BFS: var bfs = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph, vb, new Dictionary <TVertex, GraphColor>()); bfs.TreeEdge += e => { ThrowIfCancellationRequested(); _spanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target)); }; bfs.Compute(); break; case SpanningTreeGeneration.DFS: var dfs = new DepthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph); dfs.TreeEdge += e => { ThrowIfCancellationRequested(); _spanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target)); }; dfs.Compute(); break; } }
private TypeMap AddTypeToGraph(Type type) { var map = new TypeMap(type); m_TypeGraph.AddVertex(map); if ((type.BaseType != null) && (!type.BaseType.Equals(type))) { var baseMap = AddTypeToGraph(type.BaseType); m_TypeGraph.AddEdge(new Edge <TypeMap>(map, baseMap)); } if (type.IsGenericType && !type.IsGenericTypeDefinition && (type.GetGenericTypeDefinition() != null)) { var genericBaseType = type.GetGenericTypeDefinition(); if (genericBaseType != type) { var definitionMap = AddTypeToGraph(genericBaseType); m_TypeGraph.AddEdge(new Edge <TypeMap>(map, definitionMap)); } } foreach (var baseInterface in type.GetInterfaces()) { if (baseInterface != null) { var interfaceMap = AddTypeToGraph(baseInterface); m_TypeGraph.AddEdge(new Edge <TypeMap>(map, interfaceMap)); } } return(map); }
private void OnAddVertexClick(object sender, RoutedEventArgs args) { if (_graph is null || _graph.VertexCount >= 100) { return; } var random = new Random(DateTime.Now.Millisecond); int verticesToAdd = Math.Max(_graph.VertexCount / 4, 1); var parents = new string[verticesToAdd]; for (int j = 0; j < verticesToAdd; ++j) { int index = random.Next(_graph.VertexCount); parents[j] = _graph.Vertices.ElementAt(index); } for (int i = 0; i < verticesToAdd; ++i) { string newVertex; do { newVertex = $"{random.Next(0, _graph.VertexCount + 20)}_new"; } while (_graph.ContainsVertex(newVertex)); _graph.AddVertex(newVertex); if (_graph.VertexCount < 2) { return; } _graph.AddEdge(new Edge <string>(parents[i], newVertex)); } }
private void CreateGraphToVisualize(DatabaseViewModel databaseViewModel) { var g = new BidirectionalGraph <object, IEdge <object> >(); foreach (var tab in databaseViewModel.agdsModel.GetTables()) { g.AddVertex(tab.TableName); foreach (var attr in databaseViewModel.agdsModel.GetAttributes(tab)) { g.AddVertex(attr.ColumnName); g.AddEdge(new Edge <object>(tab.TableName, attr.ColumnName)); foreach (var attrVal in databaseViewModel.agdsModel.GetAttributeValues(attr)) { g.AddVertex(attrVal.Value.ToString()); g.AddEdge(new Edge <object>(attr.ColumnName, attrVal.Value.ToString())); foreach (var item in databaseViewModel.agdsModel.GetItems(attrVal)) { g.AddVertex(item.Print()); g.AddEdge(new Edge <object>(attrVal.Value.ToString(), item.Print())); foreach (var it in databaseViewModel.agdsModel.GetAssociatedItems(item)) { g.AddVertex(it.Print()); g.AddEdge(new Edge <object>(item.Print(), it.Print())); g.AddEdge(new Edge <object>(it.Print(), item.Print())); } } } } } graphToVisualize = g; }
public void NonAcyclic() { var g = new BidirectionalGraph <string, Edge <string> >(); var vs = new string[4]; for (int i = 1; i < 5; i++) { vs[i - 1] = i.ToString(); g.AddVertex(i.ToString()); } g.AddEdge(new Edge <string>(vs[0], vs[1])); g.AddEdge(new Edge <string>(vs[1], vs[2])); g.AddEdge(new Edge <string>(vs[2], vs[0])); g.AddEdge(new Edge <string>(vs[3], vs[0])); try { var lts = new LayeredTopologicalSortAlgorithm <string, Edge <string> >(g); lts.Compute(); Assert.Fail("It does not throw exception for non acyclic graphs."); } catch (NonAcyclicGraphException ex) { Debug.WriteLine(ex.Message); } }
public void MultipleSource() { var g = new BidirectionalGraph <string, Edge <string> >(); var vs = new string[5]; for (int i = 1; i < 6; i++) { vs[i - 1] = i.ToString(); g.AddVertex(i.ToString()); } g.AddEdge(new Edge <string>(vs[0], vs[1])); g.AddEdge(new Edge <string>(vs[1], vs[2])); g.AddEdge(new Edge <string>(vs[3], vs[1])); g.AddEdge(new Edge <string>(vs[4], vs[2])); var lts = new LayeredTopologicalSortAlgorithm <string, Edge <string> >(g); lts.Compute(); Assert.AreEqual(0, lts.LayerIndices[vs[0]]); Assert.AreEqual(1, lts.LayerIndices[vs[1]]); Assert.AreEqual(2, lts.LayerIndices[vs[2]]); Assert.AreEqual(0, lts.LayerIndices[vs[3]]); Assert.AreEqual(0, lts.LayerIndices[vs[4]]); }
public void SetUp() { var state1 = new NodeViewModel() { ID = 1, IsInitial = true }; var state2 = new NodeViewModel() { ID = 2, IsFinal = true }; graph = new BidirectionalGraph <NodeViewModel, EdgeViewModel>(); graph.AddVertex(state1); graph.AddVertex(state2); graph.AddEdge(new EdgeViewModel(state1, state1) { TransitionTokensString = "1" }); graph.AddEdge(new EdgeViewModel(state1, state2) { TransitionTokensString = "0" }); graph.AddEdge(new EdgeViewModel(state2, state1) { TransitionTokensString = "1" }); executor = new FAExecutor(graph); }
public void RunWithNonPassableEdgeSet() { var condition = new Mock <IScheduleCondition>(); { condition.Setup(c => c.CanTraverse(It.IsAny <CancellationToken>())) .Returns(false); } var conditionStorage = ScheduleConditionStorage.CreateInstanceWithoutTimeline(); var conditionInfo = conditionStorage.Add(condition.Object, "a", "b"); Schedule schedule; { var graph = new BidirectionalGraph <IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var middle1 = new InsertVertex(3); graph.AddVertex(middle1); var middle2 = new InsertVertex(4); graph.AddVertex(middle2); graph.AddEdge(new ScheduleEdge(start, middle1, conditionInfo.Id)); graph.AddEdge(new ScheduleEdge(start, middle2, conditionInfo.Id)); graph.AddEdge(new ScheduleEdge(middle1, end)); graph.AddEdge(new ScheduleEdge(middle2, end)); schedule = new Schedule(graph, start, end); } using (var info = new ScheduleExecutionInfo(new CurrentThreadTaskScheduler())) { using (var executor = new ScheduleExecutor( new List <IProcesExecutableScheduleVertices> { new StartVertexProcessor(), new EndVertexProcessor(), new InsertVertexProcessor(), }, conditionStorage, schedule, new ScheduleId(), info)) { var state = ScheduleExecutionState.None; executor.OnFinish += (s, e) => { state = e.State; }; executor.Start(); Assert.AreEqual(ScheduleExecutionState.NoTraversableEdgeFound, state); } } }
public void RunWithBlockingConditionOnSecondEdge() { var condition = new Mock <IScheduleCondition>(); { condition.Setup(c => c.CanTraverse(It.IsAny <CancellationToken>())) .Returns(false); } var conditionStorage = ScheduleConditionStorage.CreateInstanceWithoutTimeline(); var conditionInfo = conditionStorage.Add(condition.Object, "a", "b"); Schedule schedule; { var graph = new BidirectionalGraph <IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var middle1 = new InsertVertex(3); graph.AddVertex(middle1); var middle2 = new InsertVertex(4); graph.AddVertex(middle2); graph.AddEdge(new ScheduleEdge(start, middle1)); graph.AddEdge(new ScheduleEdge(start, middle2, conditionInfo.Id)); graph.AddEdge(new ScheduleEdge(middle1, end)); graph.AddEdge(new ScheduleEdge(middle2, end)); schedule = new Schedule(graph, start, end); } using (var info = new ScheduleExecutionInfo(new CurrentThreadTaskScheduler())) { using (var executor = new ScheduleExecutor( new List <IProcesExecutableScheduleVertices> { new StartVertexProcessor(), new EndVertexProcessor(), new InsertVertexProcessor(), }, conditionStorage, schedule, new ScheduleId(), info)) { var executionOrder = new List <int>(); executor.OnVertexProcess += (s, e) => executionOrder.Add(e.Vertex); executor.Start(); Assert.That(executionOrder, Is.EquivalentTo(new[] { 1, 3, 2 })); } } }
public void Repro13160() { // create a new graph var graph = new BidirectionalGraph <int, SEquatableEdge <int> >(false); // adding vertices for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { graph.AddVertex(i * 3 + j); } } // adding Width edges for (int i = 0; i < 3; ++i) { for (int j = 0; j < 2; ++j) { graph.AddEdge(new SEquatableEdge <int>(i * 3 + j, i * 3 + j + 1)); } } // adding Length edges for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { graph.AddEdge(new SEquatableEdge <int>(i * 3 + j, (i + 1) * 3 + j)); } } // create cross edges foreach (var e in graph.Edges) { graph.AddEdge(new SEquatableEdge <int>(e.Target, e.Source)); } // breaking graph apart for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (i == 1) { graph.RemoveVertex(i * 3 + j); } } } var target = new CyclePoppingRandomTreeAlgorithm <int, SEquatableEdge <int> >(graph); target.Compute(2); foreach (var kv in target.Successors) { Console.WriteLine("{0}: {1}", kv.Key, kv.Value); } }
public void SubScheduleWithLinkBackToParent() { var id = new ScheduleId(); var subScheduleId = new ScheduleId(); ISchedule subSchedule; { var subGraph = new BidirectionalGraph <IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); var end = new EndVertex(2); var vertex1 = new SubScheduleVertex(3, id); subGraph.AddVertex(start); subGraph.AddVertex(end); subGraph.AddVertex(vertex1); subGraph.AddEdge(new ScheduleEdge(start, vertex1)); subGraph.AddEdge(new ScheduleEdge(vertex1, end)); subSchedule = new Schedule(subGraph, start, end); } IScheduleVertex errorVertex; Schedule schedule; { var graph = new BidirectionalGraph <IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); var end = new EndVertex(2); var vertex1 = new SubScheduleVertex(3, subScheduleId); graph.AddVertex(start); graph.AddVertex(end); graph.AddVertex(vertex1); graph.AddEdge(new ScheduleEdge(start, vertex1)); graph.AddEdge(new ScheduleEdge(vertex1, end)); schedule = new Schedule(graph, start, end); errorVertex = vertex1; } var knownSchedules = new Mock <IStoreSchedules>(); { knownSchedules.Setup(s => s.Contains(It.IsAny <ScheduleId>())) .Returns <ScheduleId>(subScheduleId.Equals); knownSchedules.Setup(s => s.Schedule(It.IsAny <ScheduleId>())) .Returns <ScheduleId>(scheduleId => subSchedule); } var failures = new List <Tuple <ScheduleIntegrityFailureType, IScheduleVertex> >(); var verifier = new ScheduleVerifier(knownSchedules.Object); var result = verifier.IsValid( id, schedule, (f, v) => failures.Add(new Tuple <ScheduleIntegrityFailureType, IScheduleVertex>(f, v))); Assert.IsFalse(result); Assert.AreEqual(1, failures.Count); Assert.AreEqual(ScheduleIntegrityFailureType.SubScheduleLinksBackToParentSchedule, failures[0].Item1); Assert.AreSame(errorVertex, failures[0].Item2); }
// Constructor from list of blocks public CFGraph(List <IBaseBlock> blocks) { Blocks = blocks; EdgeTypes = new EdgeTypes(); // First step - construct List <CFGNode> cfg_nodes = new List <CFGNode>(blocks.Count); for (int i = 0; i < blocks.Count; i++) { cfg_nodes.Add(new CFGNode(blocks[i])); } // Second step - make connections for (int i = 0; i < cfg_nodes.Count; i++) { var lastOp = cfg_nodes[i].Value.Enumerate().Last(); if (i != cfg_nodes.Count - 1 && lastOp.Operation != LinearRepr.Values.Operation.Goto) { cfg_nodes[i].SetDirectChild(cfg_nodes[i + 1]); } if (lastOp.Operation == LinearRepr.Values.Operation.Goto || lastOp.Operation == LinearRepr.Values.Operation.CondGoto) { var gotoBlock = blocks.FirstOrDefault(b => b.Enumerate().First().Label.Equals(lastOp.Destination)); CFGNode goto_node = cfg_nodes.Find(el => el.Value == gotoBlock); cfg_nodes[i].SetGotoChild(goto_node); } } // Make IList and add as vertexes var base_cfg_nodes = cfg_nodes as IList <CFGNode> ?? cfg_nodes.ToList(); graph.AddVertexRange(base_cfg_nodes); // Add edges now foreach (var node in base_cfg_nodes) { if (node.directChild != null) { graph.AddEdge(new Edge <CFGNode>(node, node.directChild)); } if (node.gotoNode != null) { graph.AddEdge(new Edge <CFGNode>(node, node.gotoNode)); } } ClassificateEdges(); buildDominatorTree(); naturalCycleGraph = new NaturalCycleGraph(this); }
public void Repro13160() { // Create a new graph var graph = new BidirectionalGraph <int, SEquatableEdge <int> >(false); // Adding vertices for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { graph.AddVertex(i * 3 + j); } } // Adding Width edges for (int i = 0; i < 3; ++i) { for (int j = 0; j < 2; ++j) { graph.AddEdge( new SEquatableEdge <int>(i * 3 + j, i * 3 + j + 1)); } } // Adding Length edges for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { graph.AddEdge( new SEquatableEdge <int>(i * 3 + j, (i + 1) * 3 + j)); } } // Create cross edges foreach (SEquatableEdge <int> edge in graph.Edges) { graph.AddEdge(new SEquatableEdge <int>(edge.Target, edge.Source)); } // Breaking graph apart for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (i == 1) { graph.RemoveVertex(i * 3 + j); } } } var target = new CyclePoppingRandomTreeAlgorithm <int, SEquatableEdge <int> >(graph); target.Compute(2); }
public static void MergeVertices <T>(this BidirectionalGraph <T, Edge <T> > reducedGraph, T reducedVertex, IEnumerable <T> vertices) { reducedGraph.AddVertex(reducedVertex); foreach (var vertex in vertices) { reducedGraph.AddEdge(new Edge <T>(reducedVertex, vertex)); reducedGraph.AddEdge(new Edge <T>(vertex, reducedVertex)); reducedGraph.MergeVertex(vertex, (s, t) => new Edge <T>(s, t)); } }
public static BidirectionalGraph Simple() { // create a new adjacency graph BidirectionalGraph g = new BidirectionalGraph( new NamedVertexProvider(), new EdgeProvider(), false); NamedVertex u = (NamedVertex)g.AddVertex(); u.Name = "u"; NamedVertex w = (NamedVertex)g.AddVertex(); w.Name = "w"; NamedVertex x = (NamedVertex)g.AddVertex(); x.Name = "x"; NamedVertex y = (NamedVertex)g.AddVertex(); y.Name = "y"; NamedVertex z = (NamedVertex)g.AddVertex(); z.Name = "z"; NamedVertex v = (NamedVertex)g.AddVertex(); v.Name = "v"; g.AddEdge(u, x); g.AddEdge(u, v); g.AddEdge(w, z); g.AddEdge(w, y); g.AddEdge(w, u); g.AddEdge(x, v); g.AddEdge(v, y); g.AddEdge(y, x); g.AddEdge(z, y); return(g); }
public void CycleWithNoEdgesFromStart() { var knownSchedules = new Mock <IStoreSchedules>(); var verifier = new ScheduleVerifier(knownSchedules.Object); var graph = new BidirectionalGraph <IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var vertex1 = new InsertVertex(3); graph.AddVertex(vertex1); var vertex2 = new InsertVertex(4); graph.AddVertex(vertex2); var vertex3 = new InsertVertex(5); graph.AddVertex(vertex3); graph.AddEdge(new ScheduleEdge(start, end)); graph.AddEdge(new ScheduleEdge(vertex1, end)); graph.AddEdge(new ScheduleEdge(vertex1, vertex2)); graph.AddEdge(new ScheduleEdge(vertex2, vertex3)); graph.AddEdge(new ScheduleEdge(vertex3, vertex1)); var schedule = new Schedule(graph, start, end); var id = new ScheduleId(); var failures = new List <Tuple <ScheduleIntegrityFailureType, IScheduleVertex> >(); var result = verifier.IsValid( id, schedule, (f, v) => failures.Add(new Tuple <ScheduleIntegrityFailureType, IScheduleVertex>(f, v))); Assert.IsFalse(result); Assert.AreEqual(3, failures.Count); Assert.AreEqual(ScheduleIntegrityFailureType.ScheduleVertexIsNotReachableFromStart, failures[0].Item1); Assert.AreSame(vertex1, failures[0].Item2); Assert.AreEqual(ScheduleIntegrityFailureType.ScheduleVertexIsNotReachableFromStart, failures[1].Item1); Assert.AreSame(vertex2, failures[1].Item2); Assert.AreEqual(ScheduleIntegrityFailureType.ScheduleVertexIsNotReachableFromStart, failures[2].Item1); Assert.AreSame(vertex3, failures[2].Item2); }
private void CreateGraphFromANN() { BidirectionalGraph <object, IEdge <object> > g = new BidirectionalGraph <object, IEdge <object> >(); if (RNA is Kohonen) { int inputN = ((Kohonen)RNA).GetInputLayerSize(); for (int x = 0; x < inputN; x++) { g.AddVertex("Input-" + (x + 1).ToString()); } KohonenNeuron[,] layer = ((Kohonen)RNA).GetCompetitiveLayer(); for (int i = 0; i < ((Kohonen)RNA).GetCompetitiveLayerLength(); i++) { for (int j = 0; j < ((Kohonen)RNA).GetCompetitiveLayerLength(); j++) { KohonenNeuron neuron = layer[i, j]; g.AddVertex(neuron); for (int x2 = 0; x2 < inputN; x2++) { g.AddEdge(new Edge <object>("Input-" + (x2 + 1).ToString(), neuron)); } } } } else //is Backpropagation { List <BackpropagationLayer> layers = ((Backpropagation)RNA).GetLayers(); foreach (BackpropagationLayer layer in layers) { foreach (BackpropagationNeuron neuron in layer.neurons) { g.AddVertex(neuron); } } foreach (BackpropagationLayer layer in layers) { foreach (BackpropagationNeuron neuron in layer.neurons) { foreach (BackpropagationConnection conn in neuron.listConnection) { g.AddEdge(new Edge <object>(conn.neuron, neuron)); } } } } graphLayout.Graph = g; graphLayout.LayoutMode = LayoutMode.Automatic; graphLayout.LayoutAlgorithmType = "Tree"; }
public bool AddEdge(TEdge edge) { bool edgeWasAdded; lock (SyncRoot) edgeWasAdded = Graph.AddEdge(edge); if (edgeWasAdded) { EdgeAdded?.Invoke(edge); } return(edgeWasAdded); }
public void CycleWithNoEdgesFromStart() { var knownSchedules = new Mock<IStoreSchedules>(); var verifier = new ScheduleVerifier(knownSchedules.Object); var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var vertex1 = new InsertVertex(3); graph.AddVertex(vertex1); var vertex2 = new InsertVertex(4); graph.AddVertex(vertex2); var vertex3 = new InsertVertex(5); graph.AddVertex(vertex3); graph.AddEdge(new ScheduleEdge(start, end)); graph.AddEdge(new ScheduleEdge(vertex1, end)); graph.AddEdge(new ScheduleEdge(vertex1, vertex2)); graph.AddEdge(new ScheduleEdge(vertex2, vertex3)); graph.AddEdge(new ScheduleEdge(vertex3, vertex1)); var schedule = new Schedule(graph, start, end); var id = new ScheduleId(); var failures = new List<Tuple<ScheduleIntegrityFailureType, IScheduleVertex>>(); var result = verifier.IsValid( id, schedule, (f, v) => failures.Add(new Tuple<ScheduleIntegrityFailureType, IScheduleVertex>(f, v))); Assert.IsFalse(result); Assert.AreEqual(3, failures.Count); Assert.AreEqual(ScheduleIntegrityFailureType.ScheduleVertexIsNotReachableFromStart, failures[0].Item1); Assert.AreSame(vertex1, failures[0].Item2); Assert.AreEqual(ScheduleIntegrityFailureType.ScheduleVertexIsNotReachableFromStart, failures[1].Item1); Assert.AreSame(vertex2, failures[1].Item2); Assert.AreEqual(ScheduleIntegrityFailureType.ScheduleVertexIsNotReachableFromStart, failures[2].Item1); Assert.AreSame(vertex3, failures[2].Item2); }
public GraphHelperTest() { #region create directedGraph directedGraph = new BidirectionalGraph<string, Edge<string>>( ); directedGraph.AddVertex( one ); directedGraph.AddVertex( two ); directedGraph.AddVertex( three ); directedGraph.AddVertex( four ); directedGraph.AddEdge( new Edge<string>( one, four ) ); directedGraph.AddEdge( new Edge<string>( one, three ) ); directedGraph.AddEdge( new Edge<string>( four, two ) ); directedGraph.AddEdge( new Edge<string>( one, two ) ); #endregion #region create undirected graph undirectedGraph = new UndirectedBidirectionalGraph<string, Edge<string>>( directedGraph ); #endregion }
//Preparation for CTL requires all nodes without an outgoing edge to have a loop to self public void AddSelfLoops(BidirectionalGraph<CFGBlock, TaggedEdge<CFGBlock, EdgeTag>> graph) { foreach (var vertex in graph.Vertices) { if (!graph.OutEdges(vertex).Any()) { graph.AddEdge (new TaggedEdge<CFGBlock, EdgeTag> (vertex, vertex, new EdgeTag (EdgeType.Normal))); } } }
public void Simple() { var g = new BidirectionalGraph<string, Edge<string>>( ); var vs = new string[ 3 ]; for ( int i = 1; i < 4; i++ ) { vs[ i - 1 ] = i.ToString( ); g.AddVertex( i.ToString( ) ); } g.AddEdge( new Edge<string>( vs[ 0 ], vs[ 1 ] ) ); g.AddEdge( new Edge<string>( vs[ 1 ], vs[ 2 ] ) ); var lts = new LayeredTopologicalSortAlgorithm<string, Edge<string>>( g ); lts.Compute( ); Assert.AreEqual( lts.LayerIndices[ vs[ 0 ] ], 0 ); Assert.AreEqual( lts.LayerIndices[ vs[ 1 ] ], 1 ); Assert.AreEqual( lts.LayerIndices[ vs[ 2 ] ], 2 ); }
private void CreateGraphToVisualize() { var g = new BidirectionalGraph<object, IEdge<object>>(); //add the vertices to the graph string[] vertices = new string[5]; for (int i = 0; i < 5; i++) { vertices[i] = i.ToString(); g.AddVertex(vertices[i]); } //add some edges to the graph g.AddEdge(new Edge<object>(vertices[0], vertices[1])); g.AddEdge(new Edge<object>(vertices[1], vertices[2])); g.AddEdge(new Edge<object>(vertices[2], vertices[3])); g.AddEdge(new Edge<object>(vertices[3], vertices[1])); g.AddEdge(new Edge<object>(vertices[1], vertices[4])); _graphToVisualize = g; }
public static void AddEdge(BidirectionalGraph<DataVertex, DataEdge> graph, DataVertex source, DataVertex target, int? sourcePoint = null, int? targetPoint = null, int weight = 0) { var edge = new DataEdge(source, target, weight) { Text = string.Empty, SourceConnectionPointId = sourcePoint, TargetConnectionPointId = targetPoint, ToolTipText = "Label "+ source.ID }; graph.AddEdge(edge); }
// n - the number of vertices, f - min FAS, m - lower bound of the total number of arcs public BidirectionalGraph<int, Edge<int>> generate(int n, int f, int m) { Random rnd = new Random(); List<int> p = Enumerable.Range(1, n).OrderBy(x => rnd.Next()).ToList<int>(); int num_arcs = 0; int i, j; BidirectionalGraph<int, Edge<int>> graph = new BidirectionalGraph<int, Edge<int>>(false); graph.AddVertexRange(Enumerable.Range(1, n)); bool fl = false; for (int d = 0; d < f; d++) { i = rnd.Next(2, n + 1); j = rnd.Next(1, i); if (i == j) { fl =true;} graph.AddEdge(new Edge<int>(p[i - 1], p[j - 1])); num_arcs++; while (j != i) { int k = rnd.Next(j + 1, i + 1); if (k == j) { fl =true;} graph.AddEdge(new Edge<int>(p[j - 1], p[k - 1])); num_arcs++; j = k; } } if (num_arcs < m) { for (int d = 0; d < m - num_arcs; d++) { i = rnd.Next(1, n); j = rnd.Next(i + 1, n + 1); if (i == j) { fl = true; } graph.AddEdge(new Edge<int>(p[i - 1], p[j - 1])); } } return graph; }
public void MultipleSource() { var g = new BidirectionalGraph<string, Edge<string>>( ); var vs = new string[ 5 ]; for ( int i = 1; i < 6; i++ ) { vs[ i - 1 ] = i.ToString( ); g.AddVertex( i.ToString( ) ); } g.AddEdge( new Edge<string>( vs[ 0 ], vs[ 1 ] ) ); g.AddEdge( new Edge<string>( vs[ 1 ], vs[ 2 ] ) ); g.AddEdge( new Edge<string>( vs[ 3 ], vs[ 1 ] ) ); g.AddEdge( new Edge<string>( vs[ 4 ], vs[ 2 ] ) ); var lts = new LayeredTopologicalSortAlgorithm<string, Edge<string>>( g ); lts.Compute( ); Assert.AreEqual( 0, lts.LayerIndices[ vs[ 0 ] ] ); Assert.AreEqual( 1, lts.LayerIndices[ vs[ 1 ] ] ); Assert.AreEqual( 2, lts.LayerIndices[ vs[ 2 ] ] ); Assert.AreEqual( 0, lts.LayerIndices[ vs[ 3 ] ] ); Assert.AreEqual( 0, lts.LayerIndices[ vs[ 4 ] ] ); }
private void AssembleGraph(BidirectionalGraph<ParseTree, Edge<ParseTree>> graph, ParseTree parent) { if (parent.Children == null) { return; } foreach (var child in parent.Children) { graph.AddVertex(child); graph.AddEdge(new Edge<ParseTree>(parent, child)); AssembleGraph(graph, child); } }
private void BuildPropertyAccessTreeGraph(BidirectionalGraph<object, IEdge<object>> g, string root, IEnumerable<Node> nodes) { foreach (var node in nodes) { var property_node = node as PropertyNode; if (property_node == null) continue; var property_node_name = string.Format("{0} - {1}", property_node.Type.UnderlyingSystemType.Name, property_node.PropertyName); g.AddVertex(property_node_name); g.AddEdge(new Edge<object>(root, property_node_name)); if (property_node.Children.Count > 0) BuildPropertyAccessTreeGraph(g, property_node_name, property_node.Children); } }
public void Create() { var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); graph.AddEdge(new ScheduleEdge(start, end)); var schedule = new Schedule(graph, start, end); Assert.AreSame(start, schedule.Start); Assert.AreSame(end, schedule.End); Assert.That(schedule.Vertices, Is.EquivalentTo(new IScheduleVertex[] { start, end })); Assert.AreEqual(1, schedule.NumberOfOutboundConnections(start)); Assert.AreEqual(1, schedule.NumberOfInboundConnections(end)); }
public static BidirectionalGraph<object, IEdge<object>> ToBidirectionalGraph(this AssemblyDependencyGraph graph) { // convert schedule graph into generic bidirectional graph that is bindable to the WPF control var g = new BidirectionalGraph<object, IEdge<object>>(); foreach (Assembly assembly in graph.GetAssemblies()) { string fromAssemblyName = assembly.GetName().Name; g.AddVertex(fromAssemblyName); foreach (Assembly dependantAssembly in graph.GetDependantAssemblies(assembly)) { string toAssemblyName = dependantAssembly.GetName().Name; if (!g.ContainsVertex(toAssemblyName)) { g.AddVertex(toAssemblyName); } g.AddEdge(new Edge<object>(fromAssemblyName, toAssemblyName)); } } return g; }
public BidirectionalGraph<object, IEdge<object>> BuildDependencyGraph() { var g = new BidirectionalGraph<object, IEdge<object>>(); foreach (var type in Types) { g.AddVertex(type.Name); } foreach (var type in Types) { var types = type.GetUses(); foreach (var dependType in types) { if (dependType != type && dependType.Namespace == type.Namespace) g.AddEdge(new Edge<object>(type.Name, dependType.Name)); } } return g; }
public void CalculateLayout(IEnumerable<DiagramShape> tablesToLayout, IEnumerable<Connection> connectionsToLayout, double width, double height) { var graph = new BidirectionalGraph<DiagramShape, IEdge<DiagramShape>>(); idTable = new Dictionary<int, DiagramShape>(); var sizeDictionary = new Dictionary<DiagramShape, Size>(); int i = 0; foreach (var table in tablesToLayout) { idTable[i] = table; sizeDictionary.Add(table, new Size(table.ActualWidth + 100, table.ActualHeight + 100)); graph.AddVertex(table); i++; } foreach(var conn in connectionsToLayout) { graph.AddEdge(new Edge<DiagramShape>(conn.Source, conn.Target)); } //CreateAndRunFruchtermanReingoldLayout(graph, width, height); if (graph.EdgeCount == 0 || graph.VertexCount == 1) { // Sugiyama doesn't work when there are no edges. Use Kamada-Kawaii instead CreateAndRunKamadaKawaiiLayout(graph, width, height); } else { CreateAndRunEfficentSugiyamaLayout(sizeDictionary, graph); } return; }
public GcTypeHeap Merge(int minimumSize) { var merged = new BidirectionalGraph<GcType,MergedEdge<GcType,GcTypeEdge>>(false, this.graph.VertexCount); var merger = new EdgeMergeCondensationGraphAlgorithm<GcType, GcTypeEdge>( this.graph, merged, delegate(GcType type) { return type.Size >= minimumSize; }); merger.Compute(); var clone = new BidirectionalGraph<GcType, GcTypeEdge>( false, merged.VertexCount); foreach (var type in merged.Vertices) clone.AddVertex(type); foreach (var medge in merged.Edges) { GcTypeEdge edge = new GcTypeEdge(medge.Source, medge.Target); foreach (GcTypeEdge e in medge.Edges) edge.Count += e.Count; clone.AddEdge(edge); } Console.WriteLine("resulting {0} types, {1} edges", clone.VertexCount, clone.EdgeCount); return new GcTypeHeap(clone); }
/// <summary> /// Initializes a new instance of the <see cref="Schedule"/> class. /// </summary> /// <param name="information">The serialization information containing the data for the schedule.</param> /// <param name="context">The serialization context.</param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="information"/> is <see langword="null" />. /// </exception> public Schedule(SerializationInfo information, StreamingContext context) { { Lokad.Enforce.Argument(() => information); } m_Graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var vertices = new List<IScheduleVertex>(); var vertexCount = information.GetInt32(SerializationVertexCount); for (int i = 0; i < vertexCount; i++) { var type = (Type)information.GetValue( string.Format( CultureInfo.InvariantCulture, SerializationVertexType, i), typeof(Type)); var vertex = (IScheduleVertex)information.GetValue( string.Format( CultureInfo.InvariantCulture, SerializationVertex, i), type); vertices.Add(vertex); m_Graph.AddVertex(vertex); } var edgeCount = information.GetInt32(SerializationEdgeCount); for (int i = 0; i < edgeCount; i++) { var tuple = (Tuple<int, int, ScheduleElementId>)information.GetValue( string.Format( CultureInfo.InvariantCulture, SerializationEdge, i), typeof(Tuple<int, int, ScheduleElementId>)); m_Graph.AddEdge( new ScheduleEdge( vertices[tuple.Item1], vertices[tuple.Item2], tuple.Item3)); } var startIndex = information.GetInt32(SerializationStartVertex); m_Start = vertices[startIndex]; var endIndex = information.GetInt32(SerializationEndVertex); m_End = vertices[endIndex]; }
public BidirectionalGraph<object, IEdge<object>> BuildDependencyGraph() { var g = new BidirectionalGraph<object, IEdge<object>>(); foreach (var method in Methods) { g.AddVertex(method.Name); } foreach (var field in Fields) { g.AddVertex(field.Name); } foreach (var method in Methods) { foreach (var methodUse in method.MethodUses) { g.AddEdge(new Edge<object>(method.Name, methodUse.Name)); } foreach (var fieldUse in method.FieldUses) { g.AddEdge(new Edge<object>(method.Name, fieldUse.Name)); } } return g; }
private static Schedule CreateScheduleGraphWithOuterAndInnerLoop( ScheduleConditionInformation outerLoopConditionInfo, ScheduleConditionInformation innerLoopConditionInfo, ScheduleActionInformation outerLoopInfo, ScheduleActionInformation innerLoopInfo) { var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var vertex1 = new InsertVertex(3); graph.AddVertex(vertex1); var vertex2 = new InsertVertex(4); graph.AddVertex(vertex2); var vertex3 = new ExecutingActionVertex(5, outerLoopInfo.Id); graph.AddVertex(vertex3); var vertex4 = new InsertVertex(6); graph.AddVertex(vertex4); var vertex5 = new ExecutingActionVertex(7, innerLoopInfo.Id); graph.AddVertex(vertex5); graph.AddEdge(new ScheduleEdge(start, vertex1)); graph.AddEdge(new ScheduleEdge(vertex1, vertex2)); graph.AddEdge(new ScheduleEdge(vertex2, end, outerLoopConditionInfo.Id)); graph.AddEdge(new ScheduleEdge(vertex2, vertex3)); graph.AddEdge(new ScheduleEdge(vertex3, vertex1, innerLoopConditionInfo.Id)); graph.AddEdge(new ScheduleEdge(vertex3, vertex4)); graph.AddEdge(new ScheduleEdge(vertex4, vertex5)); graph.AddEdge(new ScheduleEdge(vertex5, vertex3)); return new Schedule(graph, start, end); }
public void RunWithBlockingConditionOnFirstEdge() { var condition = new Mock<IScheduleCondition>(); { condition.Setup(c => c.CanTraverse(It.IsAny<CancellationToken>())) .Returns(false); } var conditionStorage = ScheduleConditionStorage.CreateInstanceWithoutTimeline(); var conditionInfo = conditionStorage.Add(condition.Object, "a", "b"); Schedule schedule; { var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var middle1 = new InsertVertex(3); graph.AddVertex(middle1); var middle2 = new InsertVertex(4); graph.AddVertex(middle2); graph.AddEdge(new ScheduleEdge(start, middle1, conditionInfo.Id)); graph.AddEdge(new ScheduleEdge(start, middle2)); graph.AddEdge(new ScheduleEdge(middle1, end)); graph.AddEdge(new ScheduleEdge(middle2, end)); schedule = new Schedule(graph, start, end); } using (var info = new ScheduleExecutionInfo(new CurrentThreadTaskScheduler())) { using (var executor = new ScheduleExecutor( new List<IProcesExecutableScheduleVertices> { new StartVertexProcessor(), new EndVertexProcessor(), new InsertVertexProcessor(), }, conditionStorage, schedule, new ScheduleId(), info)) { var executionOrder = new List<int>(); executor.OnVertexProcess += (s, e) => executionOrder.Add(e.Vertex); executor.Start(); Assert.That(executionOrder, Is.EquivalentTo(new[] { 1, 4, 2 })); } } }
public void RunWithNonPassableEdgeSet() { var condition = new Mock<IScheduleCondition>(); { condition.Setup(c => c.CanTraverse(It.IsAny<CancellationToken>())) .Returns(false); } var conditionStorage = ScheduleConditionStorage.CreateInstanceWithoutTimeline(); var conditionInfo = conditionStorage.Add(condition.Object, "a", "b"); Schedule schedule; { var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var middle1 = new InsertVertex(3); graph.AddVertex(middle1); var middle2 = new InsertVertex(4); graph.AddVertex(middle2); graph.AddEdge(new ScheduleEdge(start, middle1, conditionInfo.Id)); graph.AddEdge(new ScheduleEdge(start, middle2, conditionInfo.Id)); graph.AddEdge(new ScheduleEdge(middle1, end)); graph.AddEdge(new ScheduleEdge(middle2, end)); schedule = new Schedule(graph, start, end); } using (var info = new ScheduleExecutionInfo(new CurrentThreadTaskScheduler())) { using (var executor = new ScheduleExecutor( new List<IProcesExecutableScheduleVertices> { new StartVertexProcessor(), new EndVertexProcessor(), new InsertVertexProcessor(), }, conditionStorage, schedule, new ScheduleId(), info)) { var state = ScheduleExecutionState.None; executor.OnFinish += (s, e) => { state = e.State; }; executor.Start(); Assert.AreEqual(ScheduleExecutionState.NoTraversableEdgeFound, state); } } }
private static ISchedule BuildThreeVertexSchedule(IScheduleVertex middle) { var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); graph.AddVertex(middle); graph.AddEdge(new ScheduleEdge(start, middle)); graph.AddEdge(new ScheduleEdge(middle, end)); return new Schedule(graph, start, end); }
public void RunWithLoop() { bool passThrough = false; var condition = new Mock<IScheduleCondition>(); { condition.Setup(c => c.CanTraverse(It.IsAny<CancellationToken>())) .Returns(() => passThrough); } var conditionStorage = ScheduleConditionStorage.CreateInstanceWithoutTimeline(); var conditionInfo = conditionStorage.Add(condition.Object, "a", "b"); var action = new Mock<IScheduleAction>(); { action.Setup(a => a.Execute(It.IsAny<CancellationToken>())) .Callback(() => passThrough = true); } var collection = ScheduleActionStorage.CreateInstanceWithoutTimeline(); var info = collection.Add( action.Object, "a", "b"); // Making a schedule that looks like: // start -> node1 --> node2 -> end // ^ | // |-- node3 <-| Schedule schedule; { var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); var vertex1 = new InsertVertex(3); graph.AddVertex(vertex1); var vertex2 = new InsertVertex(4); graph.AddVertex(vertex2); var vertex3 = new ExecutingActionVertex(5, info.Id); graph.AddVertex(vertex3); graph.AddEdge(new ScheduleEdge(start, vertex1)); graph.AddEdge(new ScheduleEdge(vertex1, vertex2)); graph.AddEdge(new ScheduleEdge(vertex2, end, conditionInfo.Id)); graph.AddEdge(new ScheduleEdge(vertex2, vertex3)); graph.AddEdge(new ScheduleEdge(vertex3, vertex1)); schedule = new Schedule(graph, start, end); } using (var executionInfo = new ScheduleExecutionInfo(new CurrentThreadTaskScheduler())) { using (var executor = new ScheduleExecutor( new List<IProcesExecutableScheduleVertices> { new StartVertexProcessor(), new EndVertexProcessor(), new InsertVertexProcessor(), new ActionVertexProcessor(collection), }, conditionStorage, schedule, new ScheduleId(), executionInfo)) { var executionOrder = new List<int>(); executor.OnVertexProcess += (s, e) => executionOrder.Add(e.Vertex); executor.Start(); Assert.That(executionOrder, Is.EquivalentTo(new[] { 1, 3, 4, 5, 3, 4, 2 })); } } }
void setElement(InfoWrapper W, int parent, int children) { BidirectionalGraph<object, IEdge<object>> L = new BidirectionalGraph<object, IEdge<object>>(); L.AddVertex(W); if (parent != 0) { InfoWrapper c = W; while (c.Parent.pString != "") { InfoWrapper p = m_pData[W.Parent.pString]; if (!L.ContainsVertex(p)) L.AddVertex(p); L.AddEdge(new Edge<object>(p, c)); if (parent == 1 || p.Name.pString == c.Name.pString) break; c = p; } } if (children != 0) { Action<InfoWrapper> T = null; T = (p) => { foreach (InfoWrapper a in m_pData.Values) if (a.Parent.pString == p.Name.pString) { if (!L.AddVertex(a)) L.AddVertex(a); L.AddEdge(new Edge<object>(p, a)); if (children != 1) T(a); } }; T(W); } graphLayout1.Graph = L; foreach (var v in graphLayout1.Children) { if (v is VertexControl) (v as VertexControl).PreviewMouseDoubleClick += graphLayout1_MouseDown; } (windowsFormsHost2.Child as System.Windows.Forms.PropertyGrid).SelectedObject = W; addWrapper(W); }
public void Register() { var graph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(); var start = new StartVertex(1); graph.AddVertex(start); var end = new EndVertex(2); graph.AddVertex(end); graph.AddEdge(new ScheduleEdge(start, end)); var schedule = new Schedule(graph, start, end); var scheduleBuilder = new Mock<IBuildFixedSchedules>(); { scheduleBuilder.Setup(s => s.Build()) .Returns(schedule); scheduleBuilder.Setup(s => s.AddExecutingAction(It.IsAny<ScheduleElementId>())) .Returns<ScheduleElementId>(s => new ExecutingActionVertex(0, s)); } var actionId = new ScheduleActionRegistrationId(typeof(string), 0, "a"); var conditionId = new ScheduleConditionRegistrationId(typeof(string), 0, "a"); var owner = new Mock<IOwnScheduleDefinitions>(); { owner.Setup( o => o.StoreSchedule( It.IsAny<ISchedule>(), It.IsAny<Dictionary<ScheduleActionRegistrationId, ScheduleElementId>>(), It.IsAny<Dictionary<ScheduleConditionRegistrationId, ScheduleElementId>>())) .Callback<ISchedule, Dictionary<ScheduleActionRegistrationId, ScheduleElementId>, Dictionary<ScheduleConditionRegistrationId, ScheduleElementId>>( (s, a, c) => { Assert.That(a.Keys, Is.EquivalentTo(new List<ScheduleActionRegistrationId> { actionId })); Assert.That(c.Keys, Is.EquivalentTo(new List<ScheduleConditionRegistrationId> { conditionId })); }); } var builder = new ScheduleDefinitionBuilder(owner.Object, scheduleBuilder.Object); var vertex = builder.AddExecutingAction(actionId); builder.LinkToEnd(vertex, conditionId); builder.Register(); }
private static BidirectionalGraph<string, Edge<string>> GenerateJarDependencyGraph(JarAnalyzer jars) { BidirectionalGraph<string, Edge<string>> g = new BidirectionalGraph<string, Edge<string>>(true); foreach(Jar jar in jars.Jars) { g.AddVertex(jar.name); } foreach (Jar jar in jars.Jars) { if (jar.Summary.OutgoingDependencies.Jar != null) { foreach (Jar dstJar in jar.Summary.OutgoingDependencies.Jar) { bool exist = false; foreach (IEdge<string> edge in g.InEdges(dstJar.Text[0])) { if (edge.Source == jar.name) { exist = true; } } if (!g.InEdges(dstJar.Text[0]).Any(v => v.Source == jar.name)) { g.AddEdge(new Edge<string>(dstJar.Text[0], jar.name)); } else { Trace.WriteLine("Warning: loop detected, skipping dependency " + dstJar.Text[0] + " -> " + jar.name); } } } } return g; }
public static IBidirectionalGraph<object, IEdge<object>> GetFlows(List<string> initialStrings, List<string> groups, List<string> modules) { BidirectionalGraph<object, IEdge<object>> graph = new BidirectionalGraph<object, IEdge<object>>(); foreach (var module in modules) { graph.AddVertex(module); } foreach (var group in groups) { var words = Extensions.GetSplittedWords(group); if (words.Count > 1) { string previousVertex = ""; for (int x = 0; x < words.Count; x++) { for (int y = 0; y < modules.Count; y++) { if (x == 0 && modules[y].Contains(words[x])) { previousVertex = modules[y]; } else if (x > 0 && modules[y].Contains(words[x])) { IEdge<object> tempEdge; if (graph.TryGetEdge(previousVertex, modules[y], out tempEdge) == false) { graph.AddEdge(new Edge<object>(previousVertex, modules[y])); } previousVertex = modules[y]; } } } } } IDictionary<object, int> weaklyConnectedComp = new Dictionary<object, int>(); graph.WeaklyConnectedComponents(weaklyConnectedComp); int uniqueStructs = weaklyConnectedComp.Values.GroupBy(x => x).Count(); for (int x = 0; x < uniqueStructs; x++) { var allKeysByValues = weaklyConnectedComp.Where(pair => pair.Value == x).Select(pair => pair.Key); List<string> roots = new List<string>(); List<string> sinks = new List<string>(); foreach (var item in initialStrings) { roots.Add(item[0].ToString() + item[1].ToString()); sinks.Add(item[item.ToString().Length - 2].ToString() + item[item.ToString().Length - 1].ToString()); } var entrance = roots.GroupBy(gr => gr).Select(gr => new { Name = gr.Key, Count = gr.Count() }).OrderByDescending(gr => gr.Count).FirstOrDefault(); var exit = sinks.GroupBy(gr => gr).Select(gr => new { Name = gr.Key, Count = gr.Count() }).OrderByDescending(gr => gr.Count).FirstOrDefault(); graph.AddVertex("Вход"); graph.AddVertex("Выход"); foreach (var module in modules) { if (module.Contains(entrance.Name)) { graph.AddEdge(new Edge<object>("Вход", module)); } if (module.Contains(exit.Name)) { graph.AddEdge(new Edge<object>(module, "Выход")); } } } return graph; }