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 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; }
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; }
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 }
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 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 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; }
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); } }
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 static BidirectionalGraph <int, IEdge <int> > FullGraph(int vertexCount = 10) { var graph = new BidirectionalGraph <int, IEdge <int> >(); for (int v = 1; v <= vertexCount; v++) { graph.AddVertex(v); for (int v2 = 1; v2 < v; v2++) { graph.AddEdge(new Edge <int>(v2, v)); } } return(graph); }
public static BidirectionalGraph <object, IEdge <object> > ConvertToGraphSharp(List <Vertice> grafo) { BidirectionalGraph <object, IEdge <object> > gr = new BidirectionalGraph <object, IEdge <object> >(); foreach (Vertice tv in grafo) { gr.AddVertex(tv); } foreach (Vertice tv in grafo) { foreach (tAresta ta in tv.tAdjascencias) { gr.AddEdge(new TaggedEdge <object, object>(tv, ta.vertice, ta.peso.ToString())); } } return(gr); }
public static BidirectionalGraph RegularLattice(int rows, int columns) { // create a new adjacency graph BidirectionalGraph g = new BidirectionalGraph( new NamedVertexProvider(), new EdgeProvider(), false); NamedVertex[,] latice = new NamedVertex[rows, columns]; // adding vertices for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { latice[i, j] = (NamedVertex)g.AddVertex(); latice[i, j].Name = String.Format("{0},{1}", i.ToString(), j.ToString()); } } // adding edges for (int i = 0; i < rows - 1; ++i) { for (int j = 0; j < columns - 1; ++j) { g.AddEdge(latice[i, j], latice[i, j + 1]); g.AddEdge(latice[i, j + 1], latice[i, j]); g.AddEdge(latice[i, j], latice[i + 1, j]); g.AddEdge(latice[i + 1, j], latice[i, j]); } } for (int j = 0; j < columns - 1; ++j) { g.AddEdge(latice[rows - 1, j], latice[rows - 1, j + 1]); g.AddEdge(latice[rows - 1, j + 1], latice[rows - 1, j]); } for (int i = 0; i < rows - 1; ++i) { g.AddEdge(latice[i, columns - 1], latice[i + 1, columns - 1]); g.AddEdge(latice[i + 1, columns - 1], latice[i, columns - 1]); } return(g); }
private void CreateGraphToVisualize(int count) { var g = new BidirectionalGraph <object, IEdge <object> >(); string[] vertices = new string[count]; for (int i = 0; i < count; i++) { vertices[i] = i.ToString(); g.AddVertex(vertices[i]); } for (int i = 2; i < count; i++) { g.AddEdge(new Edge <object>(vertices[tree[i].Item1], vertices[i])); } GraphToVisualize = g; }
public void AddNode(Node node) { Argument.NotNull(node, nameof(node)); if (node.Parent != null) { throw new ApplicationException("The node is already attached to node graph."); } lock (_graph) { if (_graph.AddVertex(node)) { OnGraphChanged(); node.Parent = this; } } }
public IBidirectionalGraph <NetworkGraphVertex, NetworkGraphEdge> GenerateNetworkGraph(SimilarityMetric similarityMetric) { var graph = new BidirectionalGraph <NetworkGraphVertex, NetworkGraphEdge>(); var dict = new Dictionary <Variety, NetworkGraphVertex>(); foreach (Variety variety in _projectService.Project.Varieties) { var vertex = new NetworkGraphVertex(variety); graph.AddVertex(vertex); dict[variety] = vertex; } foreach (VarietyPair pair in _projectService.Project.VarietyPairs) { graph.AddEdge(new NetworkGraphEdge(dict[pair.Variety1], dict[pair.Variety2], pair, similarityMetric)); } return(graph); }
/// <summary> /// Get bidirectional graph from input graph /// </summary> /// <param name="graph">GraphMapData</param> /// <returns>BidirectionalGraph</returns> public static BidirectionalGraph <string, WeightedEdge <string> > GetBidirectionalGraph(GraphMapData graph) { ICollection <NodeMapData> nodes = graph.GetNodes(); BidirectionalGraph <string, WeightedEdge <string> > bidirectionalGraph = new BidirectionalGraph <string, WeightedEdge <string> >(true, nodes.Count); foreach (NodeMapData node in nodes) { bidirectionalGraph.AddVertex(node.Id); } foreach (EdgeMapData edge in graph.GetEdges()) { WeightedEdge <string> weightedEdge = new WeightedEdge <string>(edge.Source, edge.Target, edge.Weight); bidirectionalGraph.AddEdge(weightedEdge); } return(bidirectionalGraph); }
public static IBidirectionalGraph <TVertex, TEdge> CreateGeneralGraph <TVertex, TEdge>( int vertexCount, int edgeCount, int maxDegree, bool parallelEdgeAllowed, [NotNull, InstantHandle] Func <int, TVertex> vertexFactory, [NotNull, InstantHandle] Func <TVertex, TVertex, TEdge> edgeFactory, [NotNull] Random random) where TEdge : IEdge <TVertex> { var graph = new BidirectionalGraph <TVertex, TEdge>(parallelEdgeAllowed, vertexCount); var verticesMap = new Dictionary <int, TVertex>(); for (int i = 0; i < vertexCount; ++i) { TVertex vertex = vertexFactory(i); verticesMap[i] = vertex; graph.AddVertex(vertex); } for (int i = 0; i < edgeCount; ++i) { int childIndex; int parentIndex; TVertex child; TVertex parent; do { childIndex = random.Next(vertexCount); parentIndex = random.Next(vertexCount); child = verticesMap[childIndex]; parent = verticesMap[parentIndex]; } while (childIndex == parentIndex || !parallelEdgeAllowed && graph.ContainsEdge(parent, child) || graph.Degree(parent) >= maxDegree || graph.Degree(child) >= maxDegree); // Create the edge between the 2 vertex graph.AddEdge(edgeFactory(parent, child)); } return(graph); }
public void TestMethod1() { var graph = new BidirectionalGraph <Node, Edge <Node> >(); var a = new Node { Name = "A" }; var b = new Node { Name = "B" }; var c = new Node { Name = "C" }; var d = new Node { Name = "D" }; var e = new Node { Name = "E" }; var f = new Node { Name = "F" }; var g = new Node { Name = "G" }; graph.AddVertex(a); graph.AddVertex(b); graph.AddVertex(c); graph.AddVertex(d); graph.AddVertex(e); graph.AddVertex(f); graph.AddVertex(g); graph.AddEdge(new Edge <Node>(a, b)); graph.AddEdge(new Edge <Node>(a, c)); graph.AddEdge(new Edge <Node>(a, f)); graph.AddEdge(new Edge <Node>(f, c)); graph.AddEdge(new Edge <Node>(f, e)); graph.AddEdge(new Edge <Node>(f, g)); graph.AddEdge(new Edge <Node>(f, g)); graph.AddEdge(new Edge <Node>(e, g)); graph.AddEdge(new Edge <Node>(d, e)); graph.AddEdge(new Edge <Node>(d, c)); graph.AddEdge(new Edge <Node>(b, d)); // var mm = Abc(graph, a, c); }
private void CreateGraphToVisualize() { var g = new BidirectionalGraph <object, IEdge <object> >(); string[] verticel = new string[5]; for (int i = 0; i < 5; i++) { verticel[i] = i.ToString(); g.AddVertex(verticel[i]); } g.AddEdge(new Edge <object>(verticel[0], verticel[1])); g.AddEdge(new Edge <object>(verticel[1], verticel[2])); g.AddEdge(new Edge <object>(verticel[2], verticel[3])); g.AddEdge(new Edge <object>(verticel[3], verticel[1])); g.AddEdge(new Edge <object>(verticel[1], verticel[3])); g.AddEdge(new Edge <object>(verticel[0], verticel[4])); _graphToVisualize = g; }
public ViewModel(Op <T> root) { var colors = CreateColorPalette(20); var set = new HashSet <Op <T> >(); var visitor = new OpVisitor <T>(op => { if (!set.Contains(op)) { set.Add(op); } }); root.Accept(visitor); var graph = new BidirectionalGraph <object, IEdge <object> >(); // new OpGraph(); var dico = new Dictionary <Op <T>, OpVertex>(); foreach (var op in set) { var colIndex = op.GetType().GetHashCode() % colors.Count; var opVertex = new OpVertex { Name = op.Representation, Color = colors[colIndex], Shape = op.Result?.Shape.ToString() != null ? "[" + op.Result.Shape + "]" : string.Empty }; dico[op] = opVertex; graph.AddVertex(opVertex); } foreach (var op in set) { foreach (var parent in op.Parents) { graph.AddEdge(new OpEdge(dico[parent], dico[op])); } } this.Graph = graph; }
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 setGrafoData() { gr = new BidirectionalGraph <object, IEdge <object> >(); foreach (Vertice tv in Customgrafo) { if (tv.Valor == 0) { tv.Valor = 1; } gr.AddVertex(tv); } foreach (Vertice tv in Customgrafo) { foreach (tAresta ta in tv.tAdjascencias) { gr.AddEdge(new TaggedEdge <object, object>(tv, ta.vertice, ta.peso.ToString())); } } }
public void Constructor() { var verticesPositions = new Dictionary <string, Point>(); var verticesSizes = new Dictionary <string, Size>(); const string vertex = "0"; var graph = new BidirectionalGraph <string, Edge <string> >(); graph.AddVertex(vertex); var algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, verticesSizes, vertex); AssertAlgorithmProperties(algorithm, graph); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, verticesSizes, vertex); algorithm.IterationEnded += (sender, args) => { }; AssertAlgorithmProperties(algorithm, graph, expectedReportIterationEnd: true); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, verticesSizes, vertex); algorithm.ProgressChanged += (sender, args) => { }; AssertAlgorithmProperties(algorithm, graph, expectedReportProgress: true); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, verticesSizes, vertex); algorithm.IterationEnded += (sender, args) => { }; algorithm.ProgressChanged += (sender, args) => { }; AssertAlgorithmProperties(algorithm, graph, expectedReportIterationEnd: true, expectedReportProgress: true); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, null, verticesSizes, vertex); AssertAlgorithmProperties(algorithm, graph); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, verticesPositions, verticesSizes, vertex); AssertAlgorithmProperties(algorithm, graph, verticesPositions); var parameters = new DoubleTreeLayoutParameters(); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, verticesSizes, vertex, parameters); AssertAlgorithmProperties(algorithm, graph, parameters: parameters); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, verticesPositions, verticesSizes, vertex, parameters); AssertAlgorithmProperties(algorithm, graph, verticesPositions, parameters: parameters); algorithm = new DoubleTreeLayoutAlgorithm <string, Edge <string>, IBidirectionalGraph <string, Edge <string> > >(graph, null, verticesSizes, vertex, parameters); AssertAlgorithmProperties(algorithm, graph, parameters: parameters); }
object PartOne(string input) { //var vm = new IntCode(input); //var currentPos = new Point(0, 0); //var currentStatus = Status.Empty; //var map = new Dictionary<Point, Status>(); ////var wayBack = new Dictionary<Point, Direction>(); //var shortestDistance = new Dictionary<Point, int>(); //shortestDistance[currentPos] = 0; //map[currentPos] = currentStatus; //var pointsToCheck = new Stack<Point>(); //pointsToCheck.Push(currentPos); //var g = new QuickGraph.BidirectionalGraph<Point, Edge<Point>>(); //g.AddVertex(currentPos); //FloodFill(vm, currentPos, shortestDistance, map, g); //var system = map.First(kvp => kvp.Value == Status.System).Key; //return shortestDistance[system]; var vm = new IntCode(input); var currentPos = new Point(0, 0); var currentStatus = Status.Empty; var map = new Dictionary <Point, Status>(); map[currentPos] = currentStatus; var pointsToCheck = new Stack <Point>(); pointsToCheck.Push(currentPos); var g = new BidirectionalGraph <Point, Edge <Point> >(); g.AddVertex(currentPos); FloodFill(vm, ref currentPos, map, g); var systemPoint = map.First(kvp => kvp.Value == Status.System).Key; g.ShortestPathsDijkstra(e => 1, new Point(0, 0))(systemPoint, out var path); return(path.Count()); }
public static IBidirectionalGraph <TVertex, TEdge> CreateDAG <TVertex, TEdge>( int vertexCount, int edgeCount, int maxParent, int maxChild, bool parallelEdgeAllowed, [NotNull, InstantHandle] Func <int, TVertex> vertexFactory, [NotNull, InstantHandle] Func <TVertex, TVertex, TEdge> edgeFactory, [NotNull] Random random) where TEdge : IEdge <TVertex> { var dagGraph = new BidirectionalGraph <TVertex, TEdge>(parallelEdgeAllowed, vertexCount); var verticesMap = new Dictionary <int, TVertex>(); for (int i = 0; i < vertexCount; ++i) { TVertex vertex = vertexFactory(i); verticesMap[i] = vertex; dagGraph.AddVertex(vertex); } for (int i = 0; i < edgeCount; ++i) { TVertex parent; TVertex child; do { int childIndex = random.Next(vertexCount - 1) + 1; int parentIndex = random.Next(childIndex); child = verticesMap[childIndex]; parent = verticesMap[parentIndex]; } while (!parallelEdgeAllowed && dagGraph.ContainsEdge(parent, child) || dagGraph.OutDegree(parent) >= maxChild || dagGraph.InDegree(child) >= maxParent); // Create the edge between the 2 vertex dagGraph.AddEdge(edgeFactory(parent, child)); } return(dagGraph); }
private void ShowPropertyAccessTree(PropertyAccessTree tree) { var g = new BidirectionalGraph <object, IEdge <object> >(); foreach (var node in tree.GraphDebug_GetChildren()) { var parameter_node = node as ParameterNode; if (parameter_node == null) { continue; } var parameter_node_name = string.Format("{0} - {1}", parameter_node.Type.UnderlyingSystemType.Name, parameter_node.Name); g.AddVertex(parameter_node_name); BuildPropertyAccessTreeGraph(g, parameter_node_name, parameter_node.Children); } graph_layout.Graph = g; }
private static IBidirectionalGraph <HierarchicalGraphVertex, HierarchicalGraphEdge> BuildHierarchicalGraph(IUndirectedGraph <Cluster <Variety>, ClusterEdge <Variety> > tree) { var graph = new BidirectionalGraph <HierarchicalGraphVertex, HierarchicalGraphEdge>(); var root = new HierarchicalGraphVertex(0); graph.AddVertex(root); if (tree.VertexCount > 2) { GenerateHierarchicalVertices(graph, root, tree, null, tree.GetCenter()); } else { foreach (Cluster <Variety> cluster in tree.Vertices) { GenerateHierarchicalVertices(graph, root, tree, null, cluster); } } return(graph); }
private void AddAllNormalPoints(BidirectionalGraph <Point, Edge <Point> > graph, int level) { var standardPoints = new HashSet <Point>(_map.Where(kvp => kvp.Value == '.') .Select(kvp => GetPointForLevel(kvp.Key, level))); foreach (var standardPoint in standardPoints) { graph.AddVertex(standardPoint); } foreach (var standardPoint in standardPoints) { foreach (var adj in _allDirections.Select(d => standardPoint.GetPoint(d)) .Where(standardPoints.Contains)) { var edge = new Edge <Point>(standardPoint, adj); graph.AddEdge(edge); } } }
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 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 void TryGetDistance_Throws() { // Algorithm don't use the Distances var graph = new BidirectionalGraph <int, EquatableEdge <int> >(); graph.AddVertex(1); var algorithm = new TSP <int, EquatableEdge <int>, BidirectionalGraph <int, EquatableEdge <int> > >(graph, _ => 1.0); algorithm.Compute(1); Assert.IsFalse(algorithm.TryGetDistance(1, out double _)); var graph2 = new BidirectionalGraph <TestVertex, EquatableEdge <TestVertex> >(); var algorithm2 = new TSP <TestVertex, EquatableEdge <TestVertex>, BidirectionalGraph <TestVertex, EquatableEdge <TestVertex> > >(graph2, _ => 1.0); // ReSharper disable once AssignNullToNotNullAttribute Assert.Throws <ArgumentNullException>(() => algorithm2.TryGetDistance(null, out _)); var vertex = new TestVertex(); Assert.Throws <InvalidOperationException>(() => algorithm2.TryGetDistance(vertex, out _)); }
private void CreateGraphToVisualize() { var g = new BidirectionalGraph <object, IEdge <object> >(); // add the verties to the graph string[] verties = new string[5]; for (int i = 0; i < 5; i++) { verties[i] = i.ToString(); g.AddVertex(verties[i]); } //add some edges to the graph g.AddEdge(new Edge <object>(verties[0], verties[1])); g.AddEdge(new Edge <object>(verties[1], verties[2])); g.AddEdge(new Edge <object>(verties[2], verties[3])); g.AddEdge(new Edge <object>(verties[3], verties[1])); g.AddEdge(new Edge <object>(verties[1], verties[4])); _graphToVisualize = g; }
/// <summary> /// /// </summary> /// <param name="node"></param> protected void AddNode(NodeVertex node) { // Skip if it it already been added if (graph.ContainsVertex(node)) { return; } // Add the vertex to the logic graph graph.AddVertex(node); // Create the vertex control var control = AssociatedObject.ControlFactory.CreateVertexControl(node); control.DataContext = node; //control.Visibility = Visibility.Hidden; // make them invisible (there is no layout positions yet calculated) // Create data binding for input slots and output slots var binding = new Binding(); binding.Path = new PropertyPath("InputSlots"); binding.Mode = BindingMode.TwoWay; binding.Source = node; binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; BindingOperations.SetBinding(control, NodeVertexControl.InputSlotsProperty, binding); binding = new Binding(); binding.Path = new PropertyPath("OutputSlots"); binding.Mode = BindingMode.TwoWay; binding.Source = node; binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; BindingOperations.SetBinding(control, NodeVertexControl.OutputSlotsProperty, binding); // Add vertex and control to the graph area AssociatedObject.AddVertex(node, control); AssociatedObject.RelayoutGraph(); // Connect control node.ConnectControl(control); }
public static IBidirectionalGraph <TVertex, TEdge> CreateGeneralGraph <TVertex, TEdge>(int vertexCount, int edgeCount, int maxDegree, bool parallelEdgeAllowed, Func <int, TVertex> vertexFactory, Func <TVertex, TVertex, TEdge> edgeFactory) where TEdge : IEdge <TVertex> { BidirectionalGraph <TVertex, TEdge> graph = new BidirectionalGraph <TVertex, TEdge>(false, vertexCount); Dictionary <int, TVertex> vertexMap = new Dictionary <int, TVertex>(); for (int i = 0; i < vertexCount; i++) { TVertex v = vertexFactory(i); vertexMap[i] = v; graph.AddVertex(v); } Random rnd = new Random(DateTime.Now.Millisecond); int childIndex; int parentIndex; TVertex child; TVertex parent; for (int i = 0; i < edgeCount; i++) { do { childIndex = rnd.Next(vertexCount); parentIndex = rnd.Next(vertexCount); child = vertexMap[childIndex]; parent = vertexMap[parentIndex]; }while (childIndex == parentIndex || (!parallelEdgeAllowed && graph.ContainsEdge(parent, child)) || graph.Degree(parent) >= maxDegree || graph.Degree(child) >= maxDegree); //create the edge between the 2 vertex TEdge e = edgeFactory(parent, child); graph.AddEdge(e); } return(graph); }
public Navigator() { //Vertices.CollectionChanged += (sender, args) => UpdateGraph(); //Edges.CollectionChanged += (sender, args) => UpdateGraph(); _graph = new BidirectionalGraph <FrameworkElement, Edge>(true); // add edges and vertices foreach (var child in InternalChildren.OfType <FrameworkElement>().Where(x => !(x is Edge)).ToList()) { if (_graph.AddVertex(child)) { child.AddHandler(SizeChangedEvent, (RoutedEventHandler)Layout); child.IsVisibleChanged += Layout; } var parent = child.GetValue(ParentProperty); if (parent != null) { var newEdge = new Edge(child, (FrameworkElement)parent, this); _graph.AddEdge(newEdge); } } SizeChanged += Layout; }
public void Draw(string filename = "ExpandingTree") { BidirectionalGraph <ExpandingNode, QuickGraph.Edge <ExpandingNode> > mG = new BidirectionalGraph <ExpandingNode, QuickGraph.Edge <ExpandingNode> >(); List <ExpandingNode> .Enumerator eV = nodeList.GetEnumerator(); while (eV.MoveNext()) { mG.AddVertex(eV.Current); } List <ExpandingNode> .Enumerator eV2 = nodeList.GetEnumerator(); while (eV2.MoveNext()) { List <ExpandingNode> .Enumerator eV3 = eV2.Current.childrenNodes.GetEnumerator(); while (eV3.MoveNext()) { QuickGraph.Edge <ExpandingNode> e = new Edge <ExpandingNode>(eV2.Current, eV3.Current); mG.AddEdge(e); } } var graphviz = new GraphvizAlgorithm <ExpandingNode, Edge <ExpandingNode> >(mG); //graphviz.CommonVertexFormat.Shape = GraphvizVertexShape.Record; graphviz.FormatVertex += new FormatVertexEventHandler <ExpandingNode>(FormatVertex); string dotFile = graphviz.Generate(new FileDotEngine(), filename); var diagramFile = dotFile.Replace(".dot", ".png"); string graphOutput = string.Format(@"""{0}"" -o ""{1}"" -Tpng", dotFile, diagramFile); Process.Start(new ProcessStartInfo("dot", graphOutput) { CreateNoWindow = true, UseShellExecute = false }); }
private static HoffmanPavleyRankedShortestPathAlgorithm <long, TaggedEdge <long, double> > PrepareShoterstPathAlgorithm(Map map) { var pathGraph = new BidirectionalGraph <long, TaggedEdge <long, double> >(); foreach (var vertex in map.GetEdges().Keys) { pathGraph.AddVertex(vertex); } foreach (var keyValuePair in map.GetEdgesWithDistance(true)) { foreach (var way in keyValuePair.Value) { var edge = new TaggedEdge <long, double>(keyValuePair.Key, way.Item1, way.Item2); pathGraph.AddEdge(edge); } } var alg = new HoffmanPavleyRankedShortestPathAlgorithm <long, TaggedEdge <long, double> >(pathGraph, e => e.Tag); return(alg); }
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; }
//Maximum weighted graph private IBidirectionalGraph <Node, IEdge <Node> > CreateGraph(IBidirectionalGraph <Node, IEdge <Node> > graph) { var newGraph = new BidirectionalGraph <Node, IEdge <Node> >(); var nodes = new HashSet <Node>(); foreach (var node in graph.Vertices) { var newNode = new Node(node.Id); newGraph.AddVertex(newNode); nodes.Add(newNode); } foreach (WeightedEdge <Node> edge in graph.Edges) { var source = nodes.First(node => node.Id == edge.Source.Id); var target = nodes.First(node => node.Id == edge.Target.Id); var newEdge = new WeightedEdge <Node>(source, target, edge.Weight); newGraph.AddEdge(newEdge); } return(newGraph); }
public static AdjacencyGraph Fsm() { // create a new adjacency graph AdjacencyGraph g = new BidirectionalGraph( new NamedVertexProvider(), new NamedEdgeProvider(), true); NamedEdge e = null; NamedVertex s0 = (NamedVertex)g.AddVertex(); s0.Name = "S0"; NamedVertex s1 = (NamedVertex)g.AddVertex(); s1.Name = "S1"; NamedVertex s2 = (NamedVertex)g.AddVertex(); s2.Name = "S2"; NamedVertex s3 = (NamedVertex)g.AddVertex(); s3.Name = "S3"; NamedVertex s4 = (NamedVertex)g.AddVertex(); s4.Name = "S4"; NamedVertex s5 = (NamedVertex)g.AddVertex(); s5.Name = "S5"; e = (NamedEdge)g.AddEdge(s0, s1); e.Name = "StartCalc"; e = (NamedEdge)g.AddEdge(s1, s0); e.Name = "StopCalc"; e = (NamedEdge)g.AddEdge(s1, s1); e.Name = "SelectStandard"; e = (NamedEdge)g.AddEdge(s1, s1); e.Name = "ClearDisplay"; e = (NamedEdge)g.AddEdge(s1, s2); e.Name = "SelectScientific"; e = (NamedEdge)g.AddEdge(s1, s3); e.Name = "EnterDecNumber"; e = (NamedEdge)g.AddEdge(s2, s1); e.Name = "SelectStandard"; e = (NamedEdge)g.AddEdge(s2, s2); e.Name = "SelectScientific"; e = (NamedEdge)g.AddEdge(s2, s2); e.Name = "ClearDisplay"; e = (NamedEdge)g.AddEdge(s2, s4); e.Name = "EnterDecNumber"; e = (NamedEdge)g.AddEdge(s2, s5); e.Name = "StopCalc"; e = (NamedEdge)g.AddEdge(s3, s0); e.Name = "StopCalc"; e = (NamedEdge)g.AddEdge(s3, s1); e.Name = "ClearDisplay"; e = (NamedEdge)g.AddEdge(s3, s3); e.Name = "SelectStandard"; e = (NamedEdge)g.AddEdge(s3, s3); e.Name = "EnterDecNumber"; e = (NamedEdge)g.AddEdge(s3, s4); e.Name = "SelectScientific"; e = (NamedEdge)g.AddEdge(s4, s2); e.Name = "ClearDisplay"; e = (NamedEdge)g.AddEdge(s4, s3); e.Name = "SelectStandard"; e = (NamedEdge)g.AddEdge(s4, s4); e.Name = "SelectScientific"; e = (NamedEdge)g.AddEdge(s4, s4); e.Name = "EnterDecNumber"; e = (NamedEdge)g.AddEdge(s4, s5); e.Name = "StopCalc"; e = (NamedEdge)g.AddEdge(s5, s2); e.Name = "StartCalc"; return(g); }
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 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 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 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 IBidirectionalGraph<HierarchicalGraphVertex, HierarchicalGraphEdge> BuildHierarchicalGraph(IUndirectedGraph<Cluster<Variety>, ClusterEdge<Variety>> tree) { var graph = new BidirectionalGraph<HierarchicalGraphVertex, HierarchicalGraphEdge>(); var root = new HierarchicalGraphVertex(0); graph.AddVertex(root); GenerateHierarchicalVertices(graph, root, tree, null, tree.GetCenter()); return graph; }
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; }
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 static void ImportEs(BidirectionalGraph<int, Edge<int>> WorkingGraph, int numObjects, string Filename = "C:\\Users\\perdo\\Desktop\\Test.es") { string s = ""; string[] Entries; Edge<int> Newedge; StreamReader reader = null; try { reader = new StreamReader(Filename); } catch { throw new Exception("Could not open File" + Filename); } reader.ReadLine(); reader.ReadLine(); //skipping first two useless lines if (!isUndirected) { while ((s = reader.ReadLine()) != null) { Entries = s.Split(' '); Newedge = new Edge<int>(int.Parse(Entries[0]), int.Parse(Entries[1])); if (Newedge.Source == Newedge.Target) continue; // removing self-edges WorkingGraph.AddVertex(int.Parse(Entries[0])); WorkingGraph.AddVertex(int.Parse(Entries[1])); WorkingGraph.AddEdge(Newedge); } } else // Would have to change the underlying graph structure to properly support undirected edges. Easier just to mirror each edge { while ((s = reader.ReadLine()) != null) { Entries = s.Split(' '); Newedge = new Edge<int>(int.Parse(Entries[0]), int.Parse(Entries[1])); if (Newedge.Source == Newedge.Target) continue; // removing self-edges WorkingGraph.AddVertex(int.Parse(Entries[0])); WorkingGraph.AddVertex(int.Parse(Entries[1])); WorkingGraph.AddEdge(Newedge); Newedge = new Edge<int>(int.Parse(Entries[1]), int.Parse(Entries[0])); WorkingGraph.AddEdge(Newedge); } } //Following code looks for vertices that have no incoming or outgoing edges //I debated not including it but figured i'd make this code robust var Verts = WorkingGraph.Vertices; var MissingItems = Enumerable.Range(0, numObjects); foreach (int item in MissingItems) { WorkingGraph.AddVertex(item); } reader.Close(); }
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); }
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 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 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); }
private static void GenerateHierarchicalVertices(BidirectionalGraph<HierarchicalGraphVertex, HierarchicalGraphEdge> graph, HierarchicalGraphVertex vertex, IUndirectedGraph<Cluster<Variety>, ClusterEdge<Variety>> tree, Cluster<Variety> parent, Cluster<Variety> cluster) { foreach (ClusterEdge<Variety> edge in tree.AdjacentEdges(cluster).Where(e => e.GetOtherVertex(cluster) != parent)) { Cluster<Variety> target = edge.GetOtherVertex(cluster); double depth = vertex.Depth + edge.Length; var newVertex = target.DataObjects.Count == 1 ? new HierarchicalGraphVertex(target.DataObjects.First(), depth) : new HierarchicalGraphVertex(depth); graph.AddVertex(newVertex); graph.AddEdge(new HierarchicalGraphEdge(vertex, newVertex, edge.Length)); GenerateHierarchicalVertices(graph, newVertex, tree, cluster, target); } }
private static void GenerateHierarchicalVertices(BidirectionalGraph<HierarchicalGraphVertex, HierarchicalGraphEdge> graph, HierarchicalGraphVertex vertex, IBidirectionalGraph<Cluster<Variety>, ClusterEdge<Variety>> tree, Cluster<Variety> cluster) { foreach (ClusterEdge<Variety> edge in tree.OutEdges(cluster)) { double depth = vertex.Depth + edge.Length; var newVertex = edge.Target.DataObjects.Count == 1 ? new HierarchicalGraphVertex(edge.Target.DataObjects.First(), depth) : new HierarchicalGraphVertex(depth); graph.AddVertex(newVertex); graph.AddEdge(new HierarchicalGraphEdge(vertex, newVertex, edge.Length)); GenerateHierarchicalVertices(graph, newVertex, tree, edge.Target); } }