Exemple #1
0
        public static IEnumerable <string> Get_Branch_Points_Backwards(string vertex, BidirectionalGraph <string, TaggedEdge <string, ITag> > graph)
        {
            var visited = new HashSet <string>();

            return(Get_Branch_Points_Backwards_LOCAL(vertex));

            #region Local Method
            IEnumerable <string> Get_Branch_Points_Backwards_LOCAL(string v1)
            {
                if (visited.Contains(v1))
                {
                    yield break;
                }
                if (!graph.ContainsVertex(v1))
                {
                    yield break;
                }

                if (graph.OutDegree(v1) > 1)
                {
                    visited.Add(v1);
                    yield return(v1);
                }

                foreach (var edge in graph.InEdges(v1))
                {
                    foreach (var v in Get_Branch_Points_Backwards_LOCAL(edge.Source))
                    {
                        yield return(v);
                    }
                }
            }

            #endregion
        }
Exemple #2
0
        public void BalanceUnBalancedFlowGraph()
        {
            g = GraphFactory.UnBalancedFlow();
            IVertex source = null;
            IVertex sink   = null;

            foreach (IVertex v in g.Vertices)
            {
                if (g.InDegree(v) == 0)
                {
                    source = v;
                    continue;
                }
                if (g.OutDegree(v) == 0)
                {
                    sink = v;
                    continue;
                }
            }
            Assert.IsNotNull(source);
            Assert.IsNotNull(sink);

            int vertexCount = g.VerticesCount;
            int edgeCount   = g.EdgesCount;

            algo = new GraphBalancerAlgorithm(g, source, sink);
            algo.DeficientVertexAdded += new VertexEventHandler(algo_DeficientVertexAdded);
            algo.SurplusVertexAdded   += new VertexEventHandler(algo_SurplusVertexAdded);
            algo.Balance();

            VerifyBalanced(vertexCount, edgeCount);
        }
Exemple #3
0
        private void generateGraphVisualization()
        {
            int maxLevel = 1;

            //Calculando cantidad de niveles del grafo
            foreach (GraphNode node in pensum.Vertices)
            {
                if (pensum.OutDegree(node) == 0)
                {
                    int level = getNodeLevel(node);

                    if (level > maxLevel)
                    {
                        maxLevel = level;
                    }
                }
            }

            //Renderizando un identificador lateral para cada label
            int levelY = 10;

            for (int i = 1; i <= maxLevel; i++)
            {
                LevelLabel lbl = new LevelLabel(i);
                lbl.Location = new Point(10, levelY);
                panelGrafo.Controls.Add(lbl);

                levelY += 151;
            }

            //Renderizando primero los vertices que no tienen hijos

            /*foreach (GraphNode node in pensum.Vertices)
             * {
             *  if (pensum.OutDegree(node) == 0 && pensum.InDegree(node) == 0)
             *  {
             *      panelGrafo.Controls.Add(node.Sub);
             *      node.Sub.X = currentMaxX + 2;
             *      node.Sub.Y = 0;
             *      currentMaxX++;
             *      currentMaxX++;
             *      node.Sub.Location = new Point(50 + 125 * node.Sub.X, 30 + 150 * node.Sub.Y);
             *  }
             * }*/

            //Renderizando los vértices del grafo
            foreach (GraphNode node in pensum.Vertices)
            {
                addNodeToGraphView(node, -1);
            }

            //Llamando a refresh para renderizar las aristas del grafo
            panelGrafo.Refresh();
        }
Exemple #4
0
        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);
        }
        public void HoffmanPavleyRankedShortestPathAll(BidirectionalGraph <string, Edge <string> > g)
        {
            if (g.VertexCount == 0)
            {
                return;
            }

            var weights = new Dictionary <Edge <string>, double>();

            foreach (var e in g.Edges)
            {
                weights.Add(e, g.OutDegree(e.Source) + 1);
            }

            this.HoffmanPavleyRankedShortestPath(
                g,
                weights,
                Enumerable.First(g.Vertices),
                Enumerable.Last(g.Vertices),
                g.VertexCount
                );
        }
Exemple #6
0
        public static IBidirectionalGraph <TVertex, TEdge> CreateDAG <TVertex, TEdge>(int vertexCount, int edgeCount, int maxParent, int maxChild, bool parallelEdgeAllowed, Func <int, TVertex> vertexFactory, Func <TVertex, TVertex, TEdge> edgeFactory)
            where TEdge : IEdge <TVertex>
        {
            BidirectionalGraph <TVertex, TEdge> dagGraph = 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;
                dagGraph.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 - 1) + 1;
                    parentIndex = rnd.Next(childIndex);
                    child       = vertexMap[childIndex];
                    parent      = vertexMap[parentIndex];
                }while ((!parallelEdgeAllowed && dagGraph.ContainsEdge(parent, child)) ||
                        dagGraph.OutDegree(parent) >= maxChild ||
                        dagGraph.InDegree(child) >= maxParent);

                //create the edge between the 2 vertex
                TEdge e = edgeFactory(parent, child);
                dagGraph.AddEdge(e);
            }

            return(dagGraph);
        }
Exemple #7
0
        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);
        }
Exemple #8
0
        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);
        }
        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);
        }
        private bool TryRemoveDummyEdge(InternalActivityEdge edge)
        {
            bool edgeRemoved = false;

            // If this is a single edge out or a single edge in - it adds no information to the graph and can be merged.
            var outDegree = arrowGraph.OutDegree(edge.Source);
            var inDegree  = arrowGraph.InDegree(edge.Target);

            // Remove the vertex which has no other edges connected to it
            if (outDegree == 1)
            {
                IEnumerable <InternalActivityEdge> allIncoming;
                if (!arrowGraph.TryGetInEdges(edge.Source, out allIncoming))
                {
                    allIncoming = new List <InternalActivityEdge>();
                }

                bool abortMerge = WillParallelEdgesBeCreated(allIncoming, null, edge.Target);

                if (!abortMerge)
                {
                    // Add the edges with the new source vertex
                    // And remove the old edges
                    foreach (var incomingEdge in allIncoming.ToList())
                    {
                        arrowGraph.AddEdge(new InternalActivityEdge(incomingEdge.Source, edge.Target, incomingEdge.IsCritical, incomingEdge.ActivityId));
                        arrowGraph.RemoveEdge(incomingEdge);
                    }

                    // Remove the edge which is no longer needed
                    arrowGraph.RemoveEdge(edge);

                    // Now remove the vertex which is no longer needed
                    arrowGraph.RemoveVertex(edge.Source);

                    edgeRemoved = true;
                }
            }
            else if (inDegree == 1)
            {
                IEnumerable <InternalActivityEdge> allOutgoing;
                if (!arrowGraph.TryGetOutEdges(edge.Target, out allOutgoing))
                {
                    allOutgoing = new List <InternalActivityEdge>();
                }

                bool abortMerge = WillParallelEdgesBeCreated(allOutgoing, edge.Source, null);

                if (!abortMerge)
                {
                    // Add the edges with the new source vertex
                    // And remove the old edges
                    foreach (var outgoingEdge in allOutgoing.ToList())
                    {
                        arrowGraph.AddEdge(new InternalActivityEdge(edge.Source, outgoingEdge.Target, outgoingEdge.IsCritical, outgoingEdge.ActivityId));
                        arrowGraph.RemoveEdge(outgoingEdge);
                    }

                    // Remove the edge which is no longer needed
                    arrowGraph.RemoveEdge(edge);

                    // Now remove the vertex which is no longer needed
                    arrowGraph.RemoveVertex(edge.Target);

                    edgeRemoved = true;
                }
            }


            return(edgeRemoved);
        }
Exemple #11
0
        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);
        }
Exemple #12
0
 /// <summary>
 /// Returns the number of vertices to which the current vertex connects.
 /// </summary>
 /// <param name="origin">The vertex for which the number of outbound connections should be returned.</param>
 /// <returns>The number of outbound connections for the current vertex.</returns>
 public int NumberOfOutboundConnections(IScheduleVertex origin)
 {
     return(m_Graph.OutDegree(origin));
 }
Exemple #13
0
 public int OutDegree(TVertex v) => _graph.OutDegree(v);