public void CalculateAncestorsTest() { CreateExemplaryGraphChain1(); Assert.Equal(1, _graph.InEdges(0).Count()); Assert.Equal(2, _graph.InEdges(1).Count()); Assert.Equal(2, _graph.OutEdges(0).Count()); Assert.Equal(1, _graph.OutEdges(1).Count()); }
private int addNodeToGraphView(GraphNode node, int currentY) { if (!panelGrafo.Contains(node.Sub)) { //Agregando el nodo al panel panelGrafo.Controls.Add(node.Sub); //Determinando la posición lógica del nodo en función de la posición de los nodos que ya fueron renderizados node.Sub.X = currentMaxX + 2; node.Sub.Y = currentY + 1; //Helper que nos ayuda a determinar si el nodo actual tiene más hijos pendientes de renderizar int childrenToDisplayCount = 0; //Estas variables servirán para recalcular el valor lógico de X para que quede centrado en relación a sus hijos int leftLimit = -2; int rightLimit = 0; //Iterando entre los hijos del nodo foreach (Edge <GraphNode> child in pensum.OutEdges(node)) { //Las operaciones se llevarán a cabo solamente si el nodo en cuestión no ha sido renderizado aún if (!panelGrafo.Contains(child.Target.Sub)) { //Agregando a los hijos del nodo recursivamente. La función nos devuelve la posición X del hijo. int childX = addNodeToGraphView(child.Target, currentY + 1); childrenToDisplayCount++; //Almacenando la posición X del primer y último hijo del nodo actual para luego recalcular la posición X de éste if (leftLimit == -2) { leftLimit = childX; } rightLimit = childX; } } //Si el nodo actual no tenía hijos pendientes de renderizar, la variable currentMaxX debe incrementar if (childrenToDisplayCount == 0) { currentMaxX++; currentMaxX++; } else { //Si el nodo actual tenía hijos pendientes de renderizar (los cuales en este punto ya fueron renderizados), //recalculamos su posición lógica en X para que esté centrada en relación a sus hijos node.Sub.X = (leftLimit + rightLimit) / 2; } } //Dándole al nodo su posición real en base a su posición lógica node.Sub.Location = new Point(50 + 125 * node.Sub.X, 30 + 150 * node.Sub.Y); //Devolviendo la posición X del nodo return(node.Sub.X); }
private void PopulateDescendants(Node node, HashSet <Node> descendants) { foreach (var outEdge in _graph.OutEdges(node)) { if (descendants.Add(outEdge.Target)) { PopulateDescendants(outEdge.Target, descendants); } } }
// get BasicBlocksList of all ancestors of the block public BasicBlocksList getChildren(int id) { var result = new BasicBlocksList(); var v = getBlockById(id); foreach (var edge in CFG.OutEdges(v)) { result.Add(edge.Target); } return(result); }
private static void ApplyStudentTransformation(BidirectionalGraph <Resource, AssociationViewEdge> resourceGraph) { var resources = resourceGraph.Vertices.ToList(); var studentResource = resources.FirstOrDefault(x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "Student")); var studentSchoolAssociationResource = resources.FirstOrDefault(x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "StudentSchoolAssociation")); // No student entity in the graph, nothing to do. if (studentResource == null) { return; } if (studentSchoolAssociationResource == null) { throw new EdFiSecurityException( "Unable to transform resource load graph as StudentSchoolAssociation was not found in the graph."); } // Get direct student dependencies var studentDependencies = resourceGraph.OutEdges(studentResource) .Where(e => e.Target != studentSchoolAssociationResource) .ToList(); // Add dependency on primaryRelationship path foreach (var directStudentDependency in studentDependencies) { // Re-point the edge to the primary relationships resourceGraph.RemoveEdge(directStudentDependency); resourceGraph.AddEdge(new AssociationViewEdge(studentSchoolAssociationResource, directStudentDependency.Target, directStudentDependency.AssociationView)); } }
public List <BidirectionalGraph <string, Edge <string> > > GetDatabaseConnectedComponents(BidirectionalGraph <string, Edge <string> > graph) { IncrementalConnectedComponentsAlgorithm <string, Edge <string> > a = new IncrementalConnectedComponentsAlgorithm <string, Edge <string> >(graph as IMutableVertexAndEdgeSet <string, Edge <string> >); a.Compute(); KeyValuePair <int, IDictionary <string, int> > components = a.GetComponents(); List <BidirectionalGraph <string, Edge <string> > > connectedComponents = new List <BidirectionalGraph <string, Edge <string> > >(components.Key); var grouped = components.Value.GroupBy(t => t.Value); foreach (var group in grouped) { BidirectionalGraph <string, Edge <string> > g = new BidirectionalGraph <string, Edge <string> >(true, group.Count()); foreach (var item in group) { g.AddVertex(item.Key); } foreach (var item in g.Vertices) { g.AddEdgeRange(graph.OutEdges(item)); } connectedComponents.Add(g); } return(connectedComponents); }
/// <summary> /// Traverses the schedule and applies an action to each vertex visited. /// </summary> /// <param name="start">The vertex where the traverse should be started.</param> /// <param name="vertexAction"> /// The action taken for each vertex that is encountered. The action is provided with the current vertex and /// a collection of all outbound, if <paramref name="traverseViaOutBoundVertices"/> is <see langword="true" />, /// or inbound vertices and the ID of the traversing condition. The function should return <see langword="false" /> /// to terminate the traverse. /// </param> /// <param name="traverseViaOutBoundVertices"> /// A flag indicating if the schedule should be traversed via the outbound edges of the vertices, or the inbound ones. /// </param> public void TraverseAllScheduleVertices( IScheduleVertex start, Func <IScheduleVertex, IEnumerable <Tuple <ScheduleElementId, IScheduleVertex> >, bool> vertexAction, bool traverseViaOutBoundVertices = true) { { Lokad.Enforce.Argument(() => start); Lokad.Enforce.With <UnknownScheduleVertexException>( m_Graph.ContainsVertex(start), Resources.Exceptions_Messages_UnknownScheduleVertex); Lokad.Enforce.Argument(() => vertexAction); } var nodeCounter = new List <IScheduleVertex>(); var uncheckedVertices = new Queue <IScheduleVertex>(); uncheckedVertices.Enqueue(start); while (uncheckedVertices.Count > 0) { var source = uncheckedVertices.Dequeue(); if (nodeCounter.Contains(source)) { continue; } nodeCounter.Add(source); var outEdges = traverseViaOutBoundVertices ? m_Graph.OutEdges(source) : m_Graph.InEdges(source); var traverseMap = from edge in outEdges select new Tuple <ScheduleElementId, IScheduleVertex>( edge.TraversingCondition, traverseViaOutBoundVertices ? edge.Target : edge.Source); var result = vertexAction(source, traverseMap); if (!result) { return; } foreach (var outEdge in outEdges) { uncheckedVertices.Enqueue(traverseViaOutBoundVertices ? outEdge.Target : outEdge.Source); } } }
//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 Edge <Node> Abc(BidirectionalGraph <Node, Edge <Node> > grpah, Node source, Node target) { var lst = new List <Edge <Node> >(); lst.AddRange(grpah.InEdges(source)); lst.AddRange(grpah.OutEdges(source)); var dim = lst.Select(o => new KeyValuePair <Edge <Node>, int>(o, MinRoutes(grpah, source, target, o))).ToList(); var min = dim.Min(o => o.Value); return(dim.FirstOrDefault(o => o.Value == min).Key); }
public IEnumerable <string> GetToDoList() { var sortedNodes = GetSortedNodes(); foreach (var node in sortedNodes) { if (nodeState[node.Name] == false) { continue; } var outTasks = graph.OutEdges(node); foreach (var task in outTasks) { var name = edgeList[task]; if (edgeState[name] == false) { yield return(name); } } } }
public static object firstOutEdge(this BidirectionalGraph <object, IEdge <object> > graph, object node) { var edges = graph.OutEdges(node).toList(); if (edges.Count > 0) { return(edges[0].Target); } "in graph.firstOutEdge there were no edges found for provided node".error(); return(null); }
private static Tuple <BidirectionalGraph <IScheduleVertex, ScheduleEdge>, IScheduleVertex, IScheduleVertex> CopyGraph( BidirectionalGraph <IScheduleVertex, ScheduleEdge> graph, IScheduleVertex start) { var map = new Dictionary <IScheduleVertex, IScheduleVertex>(); var newGraph = new BidirectionalGraph <IScheduleVertex, ScheduleEdge>(false); var startVertex = CloneVertex(start); newGraph.AddVertex(startVertex); map.Add(start, startVertex); var nodeCounter = new List <IScheduleVertex>(); var uncheckedVertices = new Queue <IScheduleVertex>(); uncheckedVertices.Enqueue(start); while (uncheckedVertices.Count > 0) { var source = uncheckedVertices.Dequeue(); if (nodeCounter.Contains(source)) { continue; } nodeCounter.Add(source); var outEdges = graph.OutEdges(source); foreach (var outEdge in outEdges) { var target = outEdge.Target; if (!map.ContainsKey(target)) { var targetVertex = CloneVertex(target); newGraph.AddVertex(targetVertex); map.Add(target, targetVertex); } var edgeSource = map[source]; var edgeTarget = map[target]; newGraph.AddEdge(new ScheduleEdge(edgeSource, edgeTarget, outEdge.TraversingCondition)); uncheckedVertices.Enqueue(outEdge.Target); } } var endVertex = map.First(p => p.Value is EndVertex).Value; return(new Tuple <BidirectionalGraph <IScheduleVertex, ScheduleEdge>, IScheduleVertex, IScheduleVertex>(newGraph, startVertex, endVertex)); }
public bool Split(out Task <TVertex, TEdge> taskTake, out Task <TVertex, TEdge> taskDrop) { if (!CanSplit()) { taskTake = null; taskDrop = null; return(false); } TEdge edgeForSplit = ChooseEdgeForSplit(); TVertex v1 = edgeForSplit.Source; TVertex v2 = edgeForSplit.Target; BidirectionalGraph <TVertex, TEdge> graphTake = _graph.Clone(); var weightsTake = new Dictionary <EquatableEdge <TVertex>, double>(_weight); var reverseEdge = new EquatableEdge <TVertex>(edgeForSplit.Target, edgeForSplit.Source); weightsTake.Remove(reverseEdge); graphTake.RemoveEdgeIf(edge => edge.Equals(reverseEdge)); foreach (TEdge outEdge in graphTake.OutEdges(v1)) { weightsTake.Remove(outEdge); } foreach (TEdge inEdge in graphTake.InEdges(v2)) { weightsTake.Remove(inEdge); } graphTake.ClearOutEdges(v1); graphTake.ClearInEdges(v2); var pathTake = new BidirectionalGraph <TVertex, TEdge>(Path); pathTake.AddEdge(edgeForSplit); taskTake = new Task <TVertex, TEdge>(graphTake, weightsTake, pathTake, MinCost, $"Take{edgeForSplit}"); BidirectionalGraph <TVertex, TEdge> graphDrop = _graph.Clone(); var weightsDrop = new Dictionary <EquatableEdge <TVertex>, double>(_weight); weightsDrop.Remove(edgeForSplit); graphDrop.RemoveEdge(edgeForSplit); taskDrop = new Task <TVertex, TEdge>(graphDrop, weightsDrop, new BidirectionalGraph <TVertex, TEdge>(Path), MinCost, $"Drop{edgeForSplit}"); return(true); }
private void RemoveEmptyBlocks() { //HACK: Not the most efficient way of solving this. //-||-: However it works. var lastTimeCount = int.MaxValue; var numberOfVertices = graph.Vertices.Count(); while (numberOfVertices != lastTimeCount) { var toRemove = new List <CFGBlock>(); foreach (var vertex in graph.Vertices) { int inEdgesCount = graph.InEdges(vertex).Count(); int outEdgesCount = graph.OutEdges(vertex).Count(); if (!(vertex.IsLeaf || vertex.IsRoot || vertex.IsSpecialBlock || vertex.AstEntryNode != null)) { if (inEdgesCount == 1 && outEdgesCount == 0) { toRemove.Add(vertex); } else if (inEdgesCount > 0 && outEdgesCount == 1) { foreach (var edge in graph.InEdges(vertex)) { var parent = edge.Source; var child = graph.OutEdge(vertex, 0).Target; graph.AddEdge(new TaggedEdge <CFGBlock, EdgeTag>(parent, child, edge.Tag)); toRemove.Add(vertex); } } } } foreach (var vertex in toRemove) { graph.RemoveVertex(vertex); } lastTimeCount = numberOfVertices; numberOfVertices = graph.Vertices.Count(); } }
private static void ApplyStaffTransformation(BidirectionalGraph <Resource, AssociationViewEdge> resourceGraph) { var resources = resourceGraph.Vertices.ToList(); var staffResource = resources.FirstOrDefault(x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "Staff")); var staffEdOrgEmployAssoc = resources.FirstOrDefault( x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "StaffEducationOrganizationEmploymentAssociation")); var staffEdOrgAssignAssoc = resources.FirstOrDefault( x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "StaffEducationOrganizationAssignmentAssociation")); // No staff entity in the graph, nothing to do. if (staffResource == null) { return; } if (staffEdOrgEmployAssoc == null && staffEdOrgAssignAssoc == null) { throw new EdFiSecurityException( "Unable to transform resource load graph since StaffEducationOrganizationAssignmentAssociation and" + " StaffEducationOrganizationEmploymentAssociation were not found in the graph."); } // Get direct staff dependencies var directStaffDependencies = resourceGraph.OutEdges(staffResource) .Where(e => e.Target != staffEdOrgEmployAssoc && e.Target != staffEdOrgAssignAssoc) .ToList(); // Add dependency on primaryRelationship path foreach (var directStaffDependency in directStaffDependencies) { // Re-point the edge to the primary relationships resourceGraph.RemoveEdge(directStaffDependency); resourceGraph.AddEdge(new AssociationViewEdge(staffEdOrgAssignAssoc, directStaffDependency.Target, directStaffDependency.AssociationView)); resourceGraph.AddEdge(new AssociationViewEdge(staffEdOrgEmployAssoc, directStaffDependency.Target, directStaffDependency.AssociationView)); } }
private static HashSet <ILInstruction> ComputeSourceScope(ILInstruction source, BidirectionalGraph <ILInstruction, Edge <ILInstruction> > flowGraph) { var scope = new HashSet <ILInstruction>(); var vertexStack = new Stack <ILInstruction>(); vertexStack.Push(source); while (vertexStack.TryPop(out var vertex)) { if (!scope.Contains(vertex)) { scope.Add(vertex); foreach (var edge in flowGraph.OutEdges(vertex)) { vertexStack.Push(edge.Target); } } } return(scope); }
private static List <List <string> > GetStraight(MatrixWithHeaders matrixWithHeaders) { Dictionary <object, IEnumerable <IEdge <object> > > vertexEdges = new Dictionary <object, IEnumerable <IEdge <object> > >(); BidirectionalGraph <object, IEdge <object> > graph = Graph.AdjacentyMatrixToGraph(matrixWithHeaders) as BidirectionalGraph <object, IEdge <object> >; List <List <string> > straight = new List <List <string> >(); EdgeList <string, Edge <string> > candidates = new EdgeList <string, Edge <string> >(); var matrix = matrixWithHeaders.Matrix; var headers = matrixWithHeaders.Headers; var vertexes = graph.Vertices; foreach (var item in vertexes) { var inEdges = graph.InEdges(item); var outEdges = graph.OutEdges(item); if (inEdges.Count() == 1 && outEdges.Count() == 1) { candidates.Add(new Edge <string>(inEdges.ElementAt(0).Source.ToString(), inEdges.ElementAt(0).Target.ToString())); candidates.Add(new Edge <string>(outEdges.ElementAt(0).Source.ToString(), outEdges.ElementAt(0).Target.ToString())); } } for (int x = candidates.Count() - 1; x > 0; x--) { if (candidates[x - 1].Source == candidates[x].Source && candidates[x - 1].Target == candidates[x].Target) { candidates.RemoveAt(x); } } for (int x = 0; x < candidates.Count; x++) { for (int y = x + 1; y < candidates.Count; y++) { IEdge <object> edge = null; graph.TryGetEdge(candidates[x].Source, candidates[y].Target, out edge); if (edge != null) { var existItems = candidates.Select(z => z.Source == edge.Source.ToString() && z.Target == edge.Target.ToString()).ToList(); bool exist = false; foreach (var item in existItems) { exist = exist || item; } if (exist == false) { List <string> tempList = new List <string>(); for (int z = x; z <= y; z++) { if (tempList.Contains(candidates[z].Source) == false) { tempList.Add(candidates[z].Source); } if (tempList.Contains(candidates[z].Target) == false) { tempList.Add(candidates[z].Target); } } straight.Add(tempList); } } } } return(straight); }
protected double CalculatePosition(TVertex v, TVertex parent, int l) { if (data.ContainsKey(v)) { return(-1); //this vertex is already layed out } while (l >= layers.Count) { layers.Add(new Layer()); } var layer = layers[l]; var size = sizes[v]; var d = new VertexData { parent = parent }; data[v] = d; layer.NextPosition += size.Width / 2.0; if (l > 0) { layer.NextPosition += layers[l - 1].LastTranslate; layers[l - 1].LastTranslate = 0; } layer.Size = Math.Max(layer.Size, size.Height + Parameters.LayerGap); layer.Vertices.Add(v); if (spanningTree.OutDegree(v) == 0) { d.position = layer.NextPosition; } else { double minPos = double.MaxValue; double maxPos = -double.MaxValue; //first put the children foreach (var child in spanningTree.OutEdges(v).Select(e => e.Target)) { double childPos = CalculatePosition(child, v, l + 1); if (childPos >= 0) { minPos = Math.Min(minPos, childPos); maxPos = Math.Max(maxPos, childPos); } } if (minPos != double.MaxValue) { d.position = (minPos + maxPos) / 2.0; } else { d.position = layer.NextPosition; } d.translate = Math.Max(layer.NextPosition - d.position, 0); layer.LastTranslate = d.translate; d.position += d.translate; layer.NextPosition = d.position; } layer.NextPosition += size.Width / 2.0 + Parameters.VertexGap; return(d.position); }
protected void BuildCompleteGraph() { this.completeGraph = new BidirectionalGraph<ConfigurationBase, TaggedEdge<ConfigurationBase, string>>(); Stack<ConfigurationBase> searchStack = new Stack<ConfigurationBase>(); searchStack.Push(this.InitialStep); while (searchStack.Count > 0) { if (completeGraph.VertexCount > Classes.Ultility.Ultility.SIMULATION_BOUND) { return; } if (CancelRequested) { return; } ConfigurationBase currentStep = searchStack.Pop(); List<ConfigurationBase> list = this.MakeOneMove(currentStep); foreach (ConfigurationBase step in list) { if (this.completeGraph.ContainsVertex(step)) { TaggedEdge<ConfigurationBase, string> edge = null; foreach (TaggedEdge<ConfigurationBase, string> outEdge in completeGraph.OutEdges(currentStep)) { if (outEdge.Tag == step.Event) { //duplicate edge is found edge = outEdge; break; } } if (edge == null) { edge = new TaggedEdge<ConfigurationBase, string>(currentStep, step, step.Event); this.completeGraph.AddEdge(edge); } } else { TaggedEdge<ConfigurationBase, string> edge = new TaggedEdge<ConfigurationBase, string>(currentStep, step, step.Event); this.completeGraph.AddVerticesAndEdge(edge); //this.completeGraph.AddVertex(step); searchStack.Push(step); } } } }
public IBidirectionalGraph <Cluster <T>, ClusterEdge <T> > GenerateClusters(IEnumerable <T> dataObjects) { var tree = new BidirectionalGraph <Cluster <T>, ClusterEdge <T> >(false); var clusters = new List <Cluster <T> >(); foreach (T dataObject in dataObjects) { var cluster = new Cluster <T>(dataObject) { Description = dataObject.ToString() }; clusters.Add(cluster); tree.AddVertex(cluster); } var distances = new Dictionary <UnorderedTuple <Cluster <T>, Cluster <T> >, double>(); var heights = new Dictionary <Cluster <T>, double>(); for (int i = 0; i < clusters.Count; i++) { for (int j = i + 1; j < clusters.Count; j++) { double distance = _getDistance(clusters[i].DataObjects.First(), clusters[j].DataObjects.First()); if (double.IsNaN(distance) || double.IsInfinity(distance) || distance < 0) { throw new ArgumentException("Invalid distance between data objects.", "dataObjects"); } distances[UnorderedTuple.Create(clusters[i], clusters[j])] = distance; } heights[clusters[i]] = 0; } while (clusters.Count >= 2) { int minI = 0, minJ = 0; double minDist = double.MaxValue; for (int i = 0; i < clusters.Count; i++) { for (int j = i + 1; j < clusters.Count; j++) { double dist = distances[UnorderedTuple.Create(clusters[i], clusters[j])]; if (dist < minDist) { minDist = dist; minI = i; minJ = j; } } } Cluster <T> iCluster = clusters[minI]; Cluster <T> jCluster = clusters[minJ]; distances.Remove(UnorderedTuple.Create(iCluster, jCluster)); var uCluster = new Cluster <T>(); tree.AddVertex(uCluster); double height = minDist / 2; heights[uCluster] = height; int iCount = tree.GetAllDataObjects(iCluster).Count(); double iLen = height - heights[iCluster]; if (iLen <= 0 && !tree.IsOutEdgesEmpty(iCluster)) { foreach (ClusterEdge <T> edge in tree.OutEdges(iCluster)) { tree.AddEdge(new ClusterEdge <T>(uCluster, edge.Target, edge.Length)); } tree.RemoveVertex(iCluster); } else { tree.RemoveInEdgeIf(iCluster, edge => true); tree.AddEdge(new ClusterEdge <T>(uCluster, iCluster, Math.Max(iLen, 0))); } int jCount = tree.GetAllDataObjects(jCluster).Count(); double jLen = height - heights[jCluster]; if (jLen <= 0 && !tree.IsOutEdgesEmpty(jCluster)) { foreach (ClusterEdge <T> edge in tree.OutEdges(jCluster)) { tree.AddEdge(new ClusterEdge <T>(uCluster, edge.Target, edge.Length)); } tree.RemoveVertex(jCluster); } else { tree.RemoveInEdgeIf(jCluster, edge => true); tree.AddEdge(new ClusterEdge <T>(uCluster, jCluster, Math.Max(jLen, 0))); } double iWeight = (double)iCount / (iCount + jCount); double jWeight = (double)jCount / (iCount + jCount); foreach (Cluster <T> kCluster in clusters.Where(c => c != iCluster && c != jCluster)) { UnorderedTuple <Cluster <T>, Cluster <T> > kiKey = UnorderedTuple.Create(kCluster, iCluster); UnorderedTuple <Cluster <T>, Cluster <T> > kjKey = UnorderedTuple.Create(kCluster, jCluster); distances[UnorderedTuple.Create(uCluster, kCluster)] = (iWeight * distances[kiKey]) + (jWeight * distances[kjKey]); distances.Remove(kiKey); distances.Remove(kjKey); } clusters.RemoveAt(minJ); clusters.RemoveAt(minI); clusters.Add(uCluster); } return(tree); }
private WordPair createNewGreenEdges(Word uWord, Word kWord, BidirectionalGraph <Word, Edge <Word> > graph) { Cache1.Clear(); List <SPath> paths = new List <SPath>(); foreach (var item in graph.OutEdges(uWord)) { SLink linkCU = new SLink(item.Target, uWord); linkCU.Exists = graph.ContainsEdge(uWord, item.Target); SLink linkCK = new SLink(item.Target, kWord); linkCK.Exists = graph.ContainsEdge(item.Target, kWord); SPath path = new SPath(linkCU, linkCK); paths.Add(path); Cache1.Add(item.Target.ID, true); } foreach (var item in graph.InEdges(kWord)) { if (Cache1.ContainsKey(item.Source.ID)) { continue; } SLink linkCK = new SLink(item.Source, kWord); linkCK.Exists = graph.ContainsEdge(item.Source, kWord); SLink linkCU = new SLink(item.Source, uWord); linkCU.Exists = graph.ContainsEdge(uWord, item.Source); SPath path = new SPath(linkCU, linkCK); paths.Add(path); } //calculate probability float pUK = 0; float pKU = 0; float probUK = 0; float probKU = 0; foreach (var item in paths) { if (!item.LinkCU.Exists || !item.LinkCK.Exists) //containing non-existance link { continue; } float PrCU = 0.0f; float PrKC = 0.0f; float PrCK = 0.0f; float PrUC = 0.0f; foreach (var downEdgeCU in graph.OutEdges(item.LinkCU.WordNonPivot)) //Loop through down-path from nonpivot1 to pivot { PrCU += 1.0f / LinkWeightCache[new SLink(downEdgeCU.Target, downEdgeCU.Source)]; //P(C|U) = P(C&U)/P(U) } foreach (var downEdgeCK in graph.OutEdges(item.LinkCK.WordPivot)) //Loop through down-path from pivot to nonpivot2 { PrKC += 1.0f / LinkWeightCache[new SLink(downEdgeCK.Source, downEdgeCK.Target)]; //P(K|C) = P(K&C)/P(C) } foreach (var upEdgeCK in graph.InEdges(item.LinkCK.WordNonPivot)) //Loop through up-path from nonpivot2 to pivot { PrCK += 1.0f / LinkWeightCache[new SLink(upEdgeCK.Source, upEdgeCK.Target)]; //P(C|K) = P(C&K)/P(K) } foreach (var upEdgeCU in graph.InEdges(item.LinkCU.WordPivot)) //Loop through up-path from pivot to nonpivot1 { PrUC += 1.0f / LinkWeightCache[new SLink(upEdgeCU.Target, upEdgeCU.Source)]; //P(U|C) = P(U&C)/P(C) } PrCU = 1.0f / PrCU; PrKC = 1.0f / PrKC; PrCK = 1.0f / PrCK; PrUC = 1.0f / PrUC; pUK += PrUC * PrCK; pKU += PrKC * PrCU; } probUK = pUK * pKU; WordPair pair = new WordPair(uWord, kWord); pair.Paths = paths; pair.Prob = (float)probUK; //set link weights foreach (var item in pair.Paths) { //CU if (!item.LinkCU.Exists) { float value = 0; if (LinkWeightCache.TryGetValue(item.LinkCU, out value)) { if (pair.Prob > value) { item.LinkCU.Pr = LinkWeightCache[item.LinkCU] = pair.Prob; } else { item.LinkCU.Pr = value; } } else { item.LinkCU.Pr = pair.Prob; LinkWeightCache.Add(item.LinkCU, pair.Prob); } } //CK if (!item.LinkCK.Exists) { float value = 0; if (LinkWeightCache.TryGetValue(item.LinkCK, out value)) { if (pair.Prob > value) { LinkWeightCache[item.LinkCK] = item.LinkCK.Pr = pair.Prob; } else { item.LinkCK.Pr = value; } } else { item.LinkCK.Pr = pair.Prob; LinkWeightCache.Add(item.LinkCK, pair.Prob); } } } return(pair); }
public IEnumerable <TEdge> OutEdges(TVertex v) => _graph.OutEdges(v);
public IUndirectedGraph <Cluster <T>, ClusterEdge <T> > GenerateClusters(IEnumerable <T> dataObjects) { var tree = new BidirectionalGraph <Cluster <T>, ClusterEdge <T> >(false); var clusters = new List <Cluster <T> >(); foreach (T dataObject in dataObjects) { var cluster = new Cluster <T>(dataObject) { Description = dataObject.ToString() }; clusters.Add(cluster); tree.AddVertex(cluster); } var distances = new Dictionary <UnorderedTuple <Cluster <T>, Cluster <T> >, double>(); for (int i = 0; i < clusters.Count; i++) { for (int j = i + 1; j < clusters.Count; j++) { double distance = _getDistance(clusters[i].DataObjects.First(), clusters[j].DataObjects.First()); if (double.IsNaN(distance) || double.IsInfinity(distance) || distance < 0) { throw new ArgumentException("Invalid distance between data objects.", "dataObjects"); } distances[UnorderedTuple.Create(clusters[i], clusters[j])] = distance; } } while (clusters.Count > 2) { Dictionary <Cluster <T>, double> r = clusters.ToDictionary(c => c, c => clusters.Where(oc => oc != c).Sum(oc => distances[UnorderedTuple.Create(c, oc)] / (clusters.Count - 2))); int minI = 0, minJ = 0; double minDist = 0, minQ = double.MaxValue; for (int i = 0; i < clusters.Count; i++) { for (int j = i + 1; j < clusters.Count; j++) { double dist = distances[UnorderedTuple.Create(clusters[i], clusters[j])]; double q = dist - r[clusters[i]] - r[clusters[j]]; if (q < minQ) { minQ = q; minDist = dist; minI = i; minJ = j; } } } Cluster <T> iCluster = clusters[minI]; Cluster <T> jCluster = clusters[minJ]; distances.Remove(UnorderedTuple.Create(iCluster, jCluster)); var uCluster = new Cluster <T>(); tree.AddVertex(uCluster); double iLen = (minDist / 2) + ((r[iCluster] - r[jCluster]) / 2); if (iLen <= 0 && !tree.IsOutEdgesEmpty(iCluster)) { foreach (ClusterEdge <T> edge in tree.OutEdges(iCluster)) { tree.AddEdge(new ClusterEdge <T>(uCluster, edge.Target, edge.Length)); } tree.RemoveVertex(iCluster); } else { tree.RemoveInEdgeIf(iCluster, edge => true); tree.AddEdge(new ClusterEdge <T>(uCluster, iCluster, Math.Max(iLen, 0))); } double jLen = minDist - iLen; if (jLen <= 0 && !tree.IsOutEdgesEmpty(jCluster)) { foreach (ClusterEdge <T> edge in tree.OutEdges(jCluster)) { tree.AddEdge(new ClusterEdge <T>(uCluster, edge.Target, edge.Length)); } tree.RemoveVertex(jCluster); } else { tree.RemoveInEdgeIf(jCluster, edge => true); tree.AddEdge(new ClusterEdge <T>(uCluster, jCluster, Math.Max(jLen, 0))); } foreach (Cluster <T> kCluster in clusters.Where(c => c != iCluster && c != jCluster)) { UnorderedTuple <Cluster <T>, Cluster <T> > kiKey = UnorderedTuple.Create(kCluster, iCluster); UnorderedTuple <Cluster <T>, Cluster <T> > kjKey = UnorderedTuple.Create(kCluster, jCluster); distances[UnorderedTuple.Create(kCluster, uCluster)] = (distances[kiKey] + distances[kjKey] - minDist) / 2; distances.Remove(kiKey); distances.Remove(kjKey); } clusters.RemoveAt(minJ); clusters.RemoveAt(minI); clusters.Add(uCluster); } if (clusters.Count == 2) { tree.AddEdge(new ClusterEdge <T>(clusters[1], clusters[0], distances[UnorderedTuple.Create(clusters[0], clusters[1])])); clusters.RemoveAt(0); } var unrootedTree = new UndirectedGraph <Cluster <T>, ClusterEdge <T> >(false); unrootedTree.AddVertexRange(tree.Vertices); unrootedTree.AddEdgeRange(tree.Edges); return(unrootedTree); }
private static Tuple<BidirectionalGraph<IScheduleVertex, ScheduleEdge>, IScheduleVertex, IScheduleVertex> CopyGraph( BidirectionalGraph<IScheduleVertex, ScheduleEdge> graph, IScheduleVertex start) { var map = new Dictionary<IScheduleVertex, IScheduleVertex>(); var newGraph = new BidirectionalGraph<IScheduleVertex, ScheduleEdge>(false); var startVertex = CloneVertex(start); newGraph.AddVertex(startVertex); map.Add(start, startVertex); var nodeCounter = new List<IScheduleVertex>(); var uncheckedVertices = new Queue<IScheduleVertex>(); uncheckedVertices.Enqueue(start); while (uncheckedVertices.Count > 0) { var source = uncheckedVertices.Dequeue(); if (nodeCounter.Contains(source)) { continue; } nodeCounter.Add(source); var outEdges = graph.OutEdges(source); foreach (var outEdge in outEdges) { var target = outEdge.Target; if (!map.ContainsKey(target)) { var targetVertex = CloneVertex(target); newGraph.AddVertex(targetVertex); map.Add(target, targetVertex); } var edgeSource = map[source]; var edgeTarget = map[target]; newGraph.AddEdge(new ScheduleEdge(edgeSource, edgeTarget, outEdge.TraversingCondition)); uncheckedVertices.Enqueue(outEdge.Target); } } var endVertex = map.First(p => p.Value is EndVertex).Value; return new Tuple<BidirectionalGraph<IScheduleVertex, ScheduleEdge>, IScheduleVertex, IScheduleVertex>(newGraph, startVertex, endVertex); }
private void BFS(CFGBlock root, BidirectionalGraph<CFGBlock, TaggedEdge<CFGBlock, EdgeTag>> _graph) { Console.WriteLine("Total BFS recursions: " + BFSRUNS + " Active BFS: " + activebfs + " nodes currently in graph: " + nodeList.Count); BFSRUNS++; activebfs++; Queue<CFGBlock> queue = new Queue<CFGBlock> (); queue.Enqueue (root); while (queue.Any ()) { var node = queue.Dequeue (); if (visited.Contains(node)) continue; visited.Add (node); var cNode = MakeCNode (node); if (cNode != null) cNode.graph = _graph; if (node.AstEntryNode != null && node.AstEntryNode.LocalName == AstConstants.Nodes.Expr_Include) { File output = null; resolver.TryResolveInclude (node.AstEntryNode, out output); if (output != null && !inFile.Contains(output)) { var _root = output.CFG.Roots ().Single (v => v.IsSpecialBlock); inFile.Add(output); //Console.WriteLine("Recursive call: " + output.Name); BFS (_root, (BidirectionalGraph<CFGBlock, TaggedEdge<CFGBlock, EdgeTag>>)output.CFG); //Console.WriteLine("Finished call: " + output.Name); //Console.WriteLine("Still " + inFile.Count() + " files left"); inFile.Remove(output); } } foreach (var edge in _graph.OutEdges(node)) if (!visited.Contains (edge.Target)) //No loops, please queue.Enqueue (edge.Target); } activebfs--; }
/// <summary> /// Inserts the given vertex in the position of the given insert vertex. The insert vertex will /// be removed if it has no more inserts left. /// </summary> /// <param name="insertVertex">The vertex which will be replaced.</param> /// <param name="vertexToInsert">The new vertex.</param> /// <returns>A tuple containing the insert vertices that were place before and after the newly inserted vertex.</returns> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="insertVertex"/> is <see langword="null" />. /// </exception> /// <exception cref="UnknownScheduleVertexException"> /// Thrown if <paramref name="insertVertex"/> does not exist in the current schedule. /// </exception> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="vertexToInsert"/> is <see langword="null" />. /// </exception> /// <exception cref="CannotInsertExistingVertexException"> /// Thrown if <paramref name="vertexToInsert"/> already exists in the schedule. /// </exception> /// <exception cref="NoInsertsLeftOnVertexException"> /// Thrown if <paramref name="insertVertex"/> has no more inserts left. /// </exception> public Tuple <InsertVertex, InsertVertex> InsertIn( InsertVertex insertVertex, IScheduleVertex vertexToInsert) { { Lokad.Enforce.Argument(() => insertVertex); Lokad.Enforce.With <UnknownScheduleVertexException>( m_Schedule.ContainsVertex(insertVertex), Resources.Exceptions_Messages_UnknownScheduleVertex); Lokad.Enforce.Argument(() => vertexToInsert); Lokad.Enforce.With <CannotInsertExistingVertexException>( !m_Schedule.ContainsVertex(vertexToInsert), Resources.Exceptions_Messages_CannotInsertExistingVertex); Lokad.Enforce.With <NoInsertsLeftOnVertexException>( (insertVertex.RemainingInserts == -1) || (insertVertex.RemainingInserts > 0), Resources.Exceptions_Messages_NoInsertsLeftOnVertex); } // Find the inbound and outbound edges var inbound = from edge in m_Schedule.InEdges(insertVertex) select edge; var outbound = from edge in m_Schedule.OutEdges(insertVertex) select edge; // Add the new node m_Schedule.AddVertex(vertexToInsert); // Create two new insert vertices to be placed on either side of the new vertex var count = (insertVertex.RemainingInserts != -1) ? insertVertex.RemainingInserts - 1 : -1; InsertVertex inboundInsert = null; InsertVertex outboundInsert = null; if ((count == -1) || (count > 0)) { inboundInsert = new InsertVertex(m_Schedule.VertexCount, count); m_Schedule.AddVertex(inboundInsert); m_Schedule.AddEdge(new ScheduleEdge(inboundInsert, vertexToInsert, null)); outboundInsert = new InsertVertex(m_Schedule.VertexCount, count); m_Schedule.AddVertex(outboundInsert); m_Schedule.AddEdge(new ScheduleEdge(vertexToInsert, outboundInsert, null)); } // Reconnect all the edges var inboundTarget = inboundInsert ?? vertexToInsert; var outboundSource = outboundInsert ?? vertexToInsert; foreach (var inboundEdge in inbound) { m_Schedule.AddEdge(new ScheduleEdge(inboundEdge.Source, inboundTarget, inboundEdge.TraversingCondition)); } foreach (var outboundEdge in outbound) { m_Schedule.AddEdge(new ScheduleEdge(outboundSource, outboundEdge.Target, outboundEdge.TraversingCondition)); } // Lastly remove the current insert node, which also destroys all the edges that are // connected to it. m_Schedule.RemoveVertex(insertVertex); return(new Tuple <InsertVertex, InsertVertex>(inboundInsert, outboundInsert)); }
public List <BidirectionalGraph <Word, Edge <Word> > > GetDatabaseConnectedComponents() { BidirectionalGraph <Word, Edge <Word> > graph = new BidirectionalGraph <Word, Edge <Word> >(true); //C vertexs foreach (var item in DBHelper._DictBase.CUDictbase.CtoU) { graph.AddVertex(DBHelper._DictBase.GetCWordByID(item.Key)); } //U vertexs foreach (var item in DBHelper._DictBase.CUDictbase.UtoC) { graph.AddVertex(DBHelper._DictBase.GetUWordByID(item.Key)); } //K vertexs foreach (var item in DBHelper._DictBase.CKDictbase.KtoC) { graph.AddVertex(DBHelper._DictBase.GetKWordByID(item.Key)); } //add C to U edges foreach (var item in DBHelper._DictBase.CUDictbase.CtoU) { foreach (var item2 in item.Value) { graph.AddEdge(new Edge <Word>(DBHelper._DictBase.GetCWordByID(item.Key), DBHelper._DictBase.GetUWordByID(item2))); } } //add C to K edges foreach (var item in DBHelper._DictBase.CKDictbase.CtoK) { foreach (var item2 in item.Value) { graph.AddEdge(new Edge <Word>(DBHelper._DictBase.GetCWordByID(item.Key), DBHelper._DictBase.GetKWordByID(item2))); } } if (WordRelaionGraph == null) { WordRelaionGraph = new BidirectionalGraph <Word, Edge <Word> >(true); foreach (var item in graph.Vertices) { WordRelaionGraph.AddVertex(item); } foreach (var item in graph.Edges) { WordRelaionGraph.AddEdge(item); } } IncrementalConnectedComponentsAlgorithm <Word, Edge <Word> > a = new IncrementalConnectedComponentsAlgorithm <Word, Edge <Word> >(graph as IMutableVertexAndEdgeSet <Word, Edge <Word> >); a.Compute(); KeyValuePair <int, IDictionary <Word, int> > components = a.GetComponents(); List <BidirectionalGraph <Word, Edge <Word> > > connectedComponents = new List <BidirectionalGraph <Word, Edge <Word> > >(components.Key); var grouped = components.Value.GroupBy(t => t.Value); foreach (var group in grouped) { BidirectionalGraph <Word, Edge <Word> > g = new BidirectionalGraph <Word, Edge <Word> >(true, group.Count()); foreach (var item in group) { g.AddVertex(item.Key); } foreach (var item in g.Vertices) { g.AddEdgeRange(graph.OutEdges(item)); } connectedComponents.Add(g); } return(connectedComponents); }
private WordPair createNewEdges(Word uWord, Word kWord, BidirectionalGraph <Word, Edge <Word> > semiCompleteGraph, BidirectionalGraph <Word, Edge <Word> > completeGraph)//, int uCount, int kCount) { Cache1.Clear(); List <SPath> paths = new List <SPath>(); WordPair pair = new WordPair(uWord, kWord); pair.Polysemy = 0f; foreach (var item in semiCompleteGraph.OutEdges(uWord)) // Using the updated graph with new edges { int inDegreePivot = (int)semiCompleteGraph.InDegree(item.Target); int outDegreePivot = (int)semiCompleteGraph.OutDegree(item.Target); int totalSenseEdge = (Math.Max(inDegreePivot, outDegreePivot) - 1) * (inDegreePivot + outDegreePivot); pair.Polysemy += totalSenseEdge; //Word pivot_sense = item.Target; //for (int sense = 1; sense <= totalSense; sense++) //{ //pivot_sense.Value = pivot_sense.Value + "_sense" + sense; SLink linkCU = new SLink(item.Target, uWord); linkCU.Exists = true;// semiCompleteGraph.ContainsEdge(uWord, pivot_sense); SLink linkCK = new SLink(item.Target, kWord); linkCK.Exists = semiCompleteGraph.ContainsEdge(item.Target, kWord); SPath path = new SPath(linkCU, linkCK); paths.Add(path); Cache1.Add(item.Target.ID, true); //} } foreach (var item in semiCompleteGraph.InEdges(kWord)) // Using the updated graph with new edges { if (Cache1.ContainsKey(item.Source.ID)) { continue; } int inDegreePivot = (int)semiCompleteGraph.InDegree(item.Source); int outDegreePivot = (int)semiCompleteGraph.OutDegree(item.Source); int totalSenseEdge = (Math.Max(inDegreePivot, outDegreePivot) - 1) * (inDegreePivot + outDegreePivot); pair.Polysemy += totalSenseEdge; SLink linkCK = new SLink(item.Source, kWord); linkCK.Exists = true;// semiCompleteGraph.ContainsEdge(item.Source, kWord); SLink linkCU = new SLink(item.Source, uWord); linkCU.Exists = semiCompleteGraph.ContainsEdge(uWord, item.Source); SPath path = new SPath(linkCU, linkCK); paths.Add(path); } //calculate probability //float couverage = Math.Min(uCount, kCount) / (float)Math.Max(uCount, kCount); float pUK = 0; float pKU = 0; float probUK = 0; float probKU = 0; //bool hasPolysemy = false; foreach (var item in paths) { //if (!item.LinkCU.Exists || !item.LinkCK.Exists) //containning non-existance link if (!item.LinkCU.Exists) { if (languageOption == 2) { completeGraph.AddEdge(new Edge <Word>(item.LinkCU.WordNonPivot, item.LinkCU.WordPivot)); } continue; } if (!item.LinkCK.Exists) { if (languageOption == 2) { completeGraph.AddEdge(new Edge <Word>(item.LinkCK.WordPivot, item.LinkCK.WordNonPivot)); } continue; } //if ((float)graph.InDegree(item.LinkCU.WordPivot) > 1 || (float)graph.OutDegree(item.LinkCK.WordPivot) > 1) // hasPolysemy = true; if (currentCycle == 1) { float PrCU = 1.0f / (float)semiCompleteGraph.OutDegree(item.LinkCU.WordNonPivot); //P(C|U) = P(C&U)/P(U) float PrKC = 1.0f / (float)semiCompleteGraph.OutDegree(item.LinkCK.WordPivot); //P(K|C) = P(K&C)/P(C) float PrCK = 1.0f / (float)semiCompleteGraph.InDegree(item.LinkCK.WordNonPivot); //P(C|K) = P(C&K)/P(K) float PrUC = 1.0f / (float)semiCompleteGraph.InDegree(item.LinkCU.WordPivot); //P(U|C) = P(U&C)/P(C) pKU += PrCU * PrKC; pUK += PrCK * PrUC; } else { float PrCU = 0.0f; float PrKC = 0.0f; float PrCK = 0.0f; float PrUC = 0.0f; foreach (var downEdgeCU in semiCompleteGraph.OutEdges(item.LinkCU.WordNonPivot)) //Loop through down-path from nonpivot1 to pivot { PrCU += 1.0f / LinkWeightCache[new SLink(downEdgeCU.Target, downEdgeCU.Source)]; //P(C|U) = P(C&U)/P(U) } foreach (var downEdgeCK in semiCompleteGraph.OutEdges(item.LinkCK.WordPivot)) //Loop through down-path from pivot to nonpivot2 { PrKC += 1.0f / LinkWeightCache[new SLink(downEdgeCK.Source, downEdgeCK.Target)]; //P(K|C) = P(K&C)/P(C) } foreach (var upEdgeCK in semiCompleteGraph.InEdges(item.LinkCK.WordNonPivot)) //Loop through up-path from nonpivot2 to pivot { PrCK += 1.0f / LinkWeightCache[new SLink(upEdgeCK.Target, upEdgeCK.Source)]; //P(C|K) = P(C&K)/P(K) } foreach (var upEdgeCU in semiCompleteGraph.InEdges(item.LinkCU.WordPivot)) //Loop through up-path from pivot to nonpivot1 { PrUC += 1.0f / LinkWeightCache[new SLink(upEdgeCU.Source, upEdgeCU.Target)]; //P(U|C) = P(U&C)/P(C) } PrCU = 1.0f / PrCU; PrKC = 1.0f / PrKC; PrCK = 1.0f / PrCK; PrUC = 1.0f / PrUC; pUK += PrUC * PrCK; pKU += PrKC * PrCU; } } probUK = pUK * pKU; //WordPair pair = new WordPair(uWord, kWord); //pair.HasMissingEdge = hasPolysemy; pair.Paths = paths; pair.Prob = (float)probUK; pair.Polysemy *= (1 - pair.Prob); //set link weights foreach (var item in pair.Paths) { //CU //float polysemyCost = 1 / ((float)graph.InDegree(item.LinkCU.WordPivot) * (float)graph.OutDegree(item.LinkCK.WordPivot)); if (item.LinkCU.Exists) { item.LinkCU.Pr = 1f; //polysemyCost; if (!LinkWeightCache.ContainsKey(item.LinkCU)) { LinkWeightCache.Add(item.LinkCU, item.LinkCU.Pr); } } else { //pair.HasMissingCUEdge = true; float value = 0; if (LinkWeightCache.TryGetValue(item.LinkCU, out value)) { if (pair.Prob > value) { item.LinkCU.Pr = LinkWeightCache[item.LinkCU] = pair.Prob; //polysemyCost * } else { item.LinkCU.Pr = value; } } else { item.LinkCU.Pr = pair.Prob; //polysemyCost * LinkWeightCache.Add(item.LinkCU, pair.Prob); } } //CK if (item.LinkCK.Exists) //false)// { item.LinkCK.Pr = 1f; //polysemyCost if (!LinkWeightCache.ContainsKey(item.LinkCK)) { LinkWeightCache.Add(item.LinkCK, item.LinkCK.Pr); } } else { float value = 0; if (LinkWeightCache.TryGetValue(item.LinkCK, out value)) { if (pair.Prob > value) { LinkWeightCache[item.LinkCK] = item.LinkCK.Pr = pair.Prob; //polysemyCost * } else { item.LinkCK.Pr = value; } } else { item.LinkCK.Pr = pair.Prob; //polysemyCost * LinkWeightCache.Add(item.LinkCK, pair.Prob); } } } return(pair); }
private double CalculatePosition(FrameworkElement v, FrameworkElement parent, int l, Dictionary <FrameworkElement, Size> sizes, ref List <Layer> layers, ref Dictionary <FrameworkElement, VertexData> data, BidirectionalGraph <FrameworkElement, Edge> spanningTree) { if (data.ContainsKey(v)) { return(-1); //this vertex is already layed out } while (l >= layers.Count) { layers.Add(new Layer()); } var layer = layers[l]; var size = sizes[v]; var d = new VertexData { Parent = parent }; data[v] = d; layer.NextPosition += size.Width / 2.0; if (l > 0) { layer.NextPosition += layers[l - 1].LastTranslate; layers[l - 1].LastTranslate = 0; } layer.Size = Math.Max(layer.Size, size.Height + LAYER_GAP); layer.Vertices.Add(v); if (spanningTree.OutDegree(v) == 0) { d.Position = layer.NextPosition; } else { var minPos = double.MaxValue; var maxPos = -double.MaxValue; //first put the children foreach (var child in spanningTree.OutEdges(v).Select(e => e.Target)) { var childPos = CalculatePosition(child, v, l + 1, sizes, ref layers, ref data, spanningTree); if (!(childPos >= 0)) { continue; } minPos = Math.Min(minPos, childPos); maxPos = Math.Max(maxPos, childPos); } if (Math.Abs(minPos - double.MaxValue) > 0) { d.Position = (minPos + maxPos) / 2.0; } else { d.Position = layer.NextPosition; } d.Translate = Math.Max(layer.NextPosition - d.Position, 0); layer.LastTranslate = d.Translate; d.Position += d.Translate; layer.NextPosition = d.Position; } // TODO: replace layer gap with a property per vertex, that is each vertex can have its own gap layer.NextPosition += size.Width / 2.0 + VERTEX_GAP; return(d.Position); }
private static void FindCycles <TVertex, TEdge>( this BidirectionalGraph <TVertex, TEdge> executionGraph, TVertex vertex, HashSet <TVertex> visited, List <TVertex> stack, List <Cycle <TVertex> > cycles) where TEdge : IEdge <TVertex> { // Do we have a circular dependency? if (stack.Contains(vertex)) { var cycle = new Cycle <TVertex> { Vertex = vertex.ToString(), Path = stack.SkipWhile(x => !x.Equals(vertex)) .Concat(new[] { vertex }) .ToList() }; if (_logger.IsDebugEnabled) { _logger.Debug($"Cycle found for vertex '{cycle.Vertex}': {string.Join(" --> ", cycle.Path.Select(x => x.ToString()))}"); } cycles.Add(cycle); visited.Add(vertex); return; } // If we've already evaluated this vertex, stop now. if (visited.Contains(vertex)) { return; } // Mark the current node as visited and part of recursion stack visited.Add(vertex); stack.Add(vertex); try { var children = executionGraph .OutEdges(vertex) .Select(x => x.Target) .ToList(); if (_logger.IsDebugEnabled) { if (children.Any()) { _logger.Debug($"Children of {vertex}: {string.Join(" => ", children.Select(x => x.ToString()))}"); } } foreach (var child in children) { executionGraph.FindCycles(child, visited, stack, cycles); } } finally { stack.Remove(vertex); } }
public IEnumerable <TEdge> GetOutEdges(TVertexId vertexId) => _graph.OutEdges(vertexId).Select(FromVertexIdEdge);
private List <WordPair> GeneratePossiblePairs(BidirectionalGraph <Word, Edge <Word> > g) { LinkCache = new Dictionary <int, SLink>(); LinkWeightCache = new Dictionary <SLink, float>(); graph = new BidirectionalGraph <Word, Edge <Word> >(false); semiCompleteGraph = new BidirectionalGraph <Word, Edge <Word> >(false); completeGraph = new BidirectionalGraph <Word, Edge <Word> >(false); #region Prepare graph foreach (var item in g.Vertices) { graph.AddVertex(item); semiCompleteGraph.AddVertex(item); completeGraph.AddVertex(item); } foreach (var item in g.Edges) { if (item.Source.Language == Console.Language.Chinese && item.Target.Language == Console.Language.Uyghur) { graph.AddEdge(new Edge <Word>(item.Target, item.Source)); semiCompleteGraph.AddEdge(new Edge <Word>(item.Target, item.Source)); completeGraph.AddEdge(new Edge <Word>(item.Target, item.Source)); } else { graph.AddEdge(new Edge <Word>(item.Source, item.Target)); semiCompleteGraph.AddEdge(new Edge <Word>(item.Source, item.Target)); completeGraph.AddEdge(new Edge <Word>(item.Source, item.Target)); } } #endregion List <WordPair> ooPairs = new List <WordPair>(); Dictionary <WordPair, bool> ooPairsDict = new Dictionary <WordPair, bool>(); var uWords = graph.Vertices.Where(t => t.Language == Language.Uyghur); var kWords = graph.Vertices.Where(t => t.Language == Language.Kazak); var cWords = graph.Vertices.Where(t => t.Language == Language.Chinese); //int uWordCount = uWords.Count(); //int kWordCount = kWords.Count(); //int cWordCount = cWords.Count(); int u = 0, k = 0; /*foreach (var uWord in uWords) * { * foreach (var edge1 in graph.OutEdges(uWord)) * { * foreach (var edge2 in graph.OutEdges(edge1.Target)) * { * Word kWord = edge2.Target; * WordPair ooPair = new WordPair(uWord, kWord); * ooPair = createNewEdges(uWord, kWord, graph);//, uWordCount, kWordCount); * if (ooPairsDict.ContainsKey(ooPair)) * continue; * else * { * ooPairsDict.Add(ooPair, true); * ooPairs.Add(ooPair); * } * } * } * * }*/ currentCycle = 1; while (currentCycle <= symmetryCycle) { Debug.WriteLine(currentCycle); if (currentCycle > 1) { //semiCompleteGraph.Clear(); semiCompleteGraph = completeGraph; } ooPairsDict.Clear(); ooPairs.Clear(); foreach (var uWord in uWords) { Word cWord; Word kWord; foreach (var edge1 in graph.OutEdges(uWord)) { cWord = edge1.Target; foreach (var edge2 in graph.OutEdges(cWord)) { kWord = edge2.Target; WordPair pair = new WordPair(uWord, kWord); pair = createNewEdges(uWord, kWord, semiCompleteGraph, completeGraph); if (ooPairsDict.ContainsKey(pair)) { continue; } else { ooPairsDict.Add(pair, true); ooPairs.Add(pair); } } } } currentCycle++; } /*//2nd cycle to add new blue edge and generate more pairs * //Add new pair candidate from the semiCompleteGraph * if (false)//languageOption == 2 && symmetryCycle > 1) * { * ooPairsDict.Clear(); * ooPairs.Clear(); * * foreach (var uWord in uWords) * { * Word cWord; * Word kWord; * * foreach (var edge1 in semiCompleteGraph.OutEdges(uWord)) * { * cWord = edge1.Target; * foreach (var edge2 in semiCompleteGraph.OutEdges(cWord)) * { * kWord = edge2.Target; * * WordPair pair = new WordPair(null, null); * pair = createNewBlueEdges(uWord, kWord, semiCompleteGraph); * if (ooPairsDict.ContainsKey(pair)) * continue; * else * { * ooPairsDict.Add(pair, true); * ooPairs.Add(pair); * } * } * } * } * } * * //3rd cycle to add new green edge and generate more pairs * //Add new pair candidate from the semiCompleteGraph * if (false)//languageOption == 2 && symmetryCycle > 2) * { * ooPairsDict.Clear(); * ooPairs.Clear(); * * foreach (var uWord in uWords) * { * Word cWord; * Word kWord; * * foreach (var edge1 in completeGraph.OutEdges(uWord)) * { * cWord = edge1.Target; * foreach (var edge2 in completeGraph.OutEdges(cWord)) * { * kWord = edge2.Target; * * WordPair pair = new WordPair(null, null); * pair = createNewGreenEdges(uWord, kWord, completeGraph); * if (ooPairsDict.ContainsKey(pair)) * continue; * else * { * ooPairsDict.Add(pair, true); * ooPairs.Add(pair); * } * } * } * } * }*/ float maxWeight = 0; return(ooPairs); }
private double CalculatePosition([NotNull] TVertex vertex, [CanBeNull] TVertex parent, int l) { if (_data.ContainsKey(vertex)) { return(-1); // This vertex is already layed out } while (l >= _layers.Count) { _layers.Add(new Layer()); } Layer layer = _layers[l]; Size size = _verticesSizes[vertex]; var d = new VertexData { Parent = parent }; _data[vertex] = d; layer.NextPosition += size.Width / 2.0; if (l > 0) { layer.NextPosition += _layers[l - 1].LastTranslate; _layers[l - 1].LastTranslate = 0; } layer.Size = Math.Max(layer.Size, size.Height + Parameters.LayerGap); layer.Vertices.Add(vertex); if (_spanningTree.OutDegree(vertex) == 0) { d.Position = layer.NextPosition; } else { double minPos = double.MaxValue; double maxPos = -double.MaxValue; // First put the children foreach (TVertex child in _spanningTree.OutEdges(vertex).Select(e => e.Target)) { double childPos = CalculatePosition(child, vertex, l + 1); if (childPos >= 0) { minPos = Math.Min(minPos, childPos); maxPos = Math.Max(maxPos, childPos); } } if (NearEqual(minPos, double.MaxValue)) { d.Position = layer.NextPosition; } else { d.Position = (minPos + maxPos) / 2.0; } d.Translate = Math.Max(layer.NextPosition - d.Position, 0); layer.LastTranslate = d.Translate; d.Position += d.Translate; layer.NextPosition = d.Position; } layer.NextPosition += size.Width / 2.0 + Parameters.VertexGap; return(d.Position); }
public void ReadGraph(TextReader reader) { var g = new BidirectionalGraph<MyType, IEdge<MyType>>(); try { var csv = new CsvHelper.CsvReader(reader); while (csv.Read()) { if (!csv.CurrentRecord.Any()) { continue; } var node = csv.CurrentRecord.First(); var edges = csv.CurrentRecord.Skip(1) .Where(x => !string.IsNullOrEmpty(x)) .Select(x => x.Trim()) .Where(x => !string.IsNullOrEmpty(x)); foreach (var edge in edges) { g.AddVerticesAndEdge(new Edge<MyType>(node, edge)); } } var dict = new Dictionary<int, HashSet<MyType>>(); HashSet<MyType> set; foreach (var v in g.Vertices) { var edgeCount = g.InEdges(v).Count(); if (!dict.TryGetValue(edgeCount, out set)) { set = new HashSet<MyType>(); dict.Add(edgeCount, set); } set.Add(v); } Graph = g; Summary = string.Join(Environment.NewLine, dict .OrderBy(kvp => kvp.Key) .Select(kvp => kvp.Key + ": " + string.Join(", ", kvp.Value))) + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, g.Vertices .Where(v => g.OutEdges(v).Count() != 3) .Select(v => v + ": " + g.OutEdges(v).Count())); //Summary = string.Join( // Environment.NewLine, // graph.Vertices // .OrderBy(x => graph.InEdges(x).Count()) // .Select(v => v + ": " + graph.InEdges(v).Count())); } catch (Exception e) { Summary = "Failed to read:" + Environment.NewLine + e; } }