Ejemplo n.º 1
0
 private void SetChainPositions(VertexListMatrix chains, VertexIntDictionary chain_number, VertexIntDictionary pos_in_chain)
 //	Record chain number and position in chain of each vertex in chains
 {
     if (chain_number == null)
     {
         throw new ArgumentNullException("chain_number");
     }
     if (pos_in_chain == null)
     {
         throw new ArgumentNullException("pos_in_chain");
     }
     for (int i = 0; i < chains.RowCount; i++)
     {
         for (int j = 0; j < chains[i].Count; j++)
         {
             IVertex v = (IVertex)chains[i][j];
             if (!chain_number.ContainsKey(v))
             {
                 chain_number.Add(v, i);
             }
             if (!pos_in_chain.ContainsKey(v))
             {
                 pos_in_chain.Add(v, j);
             }
         }
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Create a collection of odd vertices
        /// </summary>
        /// <param name="g">graph to visit</param>
        /// <returns>colleciton of odd vertices</returns>
        /// <exception cref="ArgumentNullException">g is a null reference</exception>
        public static VertexCollection OddVertices(IVertexAndEdgeListGraph g)
        {
            if (g == null)
            {
                throw new ArgumentNullException("g");
            }

            VertexIntDictionary counts = new VertexIntDictionary();

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

            foreach (IEdge e in g.Edges)
            {
                ++counts[e.Source];
                --counts[e.Target];
            }

            VertexCollection odds = new VertexCollection();

            foreach (DictionaryEntry de in counts)
            {
                if ((int)de.Value % 2 != 0)
                {
                    odds.Add((IVertex)de.Key);
                }
            }

            return(odds);
        }
Ejemplo n.º 3
0
        protected void Initialize()
        {
            this.costs                    = new VertexDoubleDictionary();
            this.priorityQueue            = new PriorithizedVertexBuffer(costs);
            this.unvisitedSuccessorCounts = new VertexIntDictionary();
            this.states.Clear();

            foreach (IVertex v in this.goals)
            {
                this.costs.Add(v, 0);
                this.priorityQueue.Push(v);
            }

            foreach (IVertex v in this.NotGoals)
            {
                this.costs.Add(v, double.PositiveInfinity);
            }

            foreach (IVertex v in this.TestGraph.ChoicePoints)
            {
                this.unvisitedSuccessorCounts.Add(v, this.testGraph.Graph.OutDegree(v));
            }

            foreach (IVertex v in this.TestGraph.Graph.Vertices)
            {
                this.states.Add(v, null);
            }
        }
 public void Init()
 {
     m_Parents       = new VertexVertexDictionary();
     m_DiscoverTimes = new VertexIntDictionary();
     m_FinishTimes   = new VertexIntDictionary();
     m_Time          = 0;
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Clear the extracted strongly connected components
 /// </summary>
 public void ClearComponents()
 {
     this.components = null;
     if (sccVertexMap != null)
     {
         sccVertexMap.Clear();
     }
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="g"></param>
 public ConnectedComponentsAlgorithm(IVertexListGraph g)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     m_VisitedGraph = g;
     m_Components   = new VertexIntDictionary();
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Computes the strong components.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Thread safe.
        /// </para>
        /// </remarks>
        /// <param name="g">graph to explore</param>
        /// <param name="components">component map where results are recorded</param>
        /// <returns>number of strong components</returns>
        public static int StrongComponents(
            IVertexListGraph g,
            VertexIntDictionary components)
        {
            StrongComponentsAlgorithm strong =
                new StrongComponentsAlgorithm(g, components);

            return(strong.Compute());
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Computes the connected components.
        /// </summary>
        /// <param name="g">graph to explore</param>
        /// <param name="components">component map where results are recorded</param>
        /// <returns>number of components</returns>
        public static int ConnectedComponents(
            IVertexListGraph g,
            VertexIntDictionary components)
        {
            ConnectedComponentsAlgorithm conn =
                new ConnectedComponentsAlgorithm(g, components);

            return(conn.Compute());
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Condensation Graph constructor
 /// </summary>
 /// <param name="g">Input graph from
 /// which condensation graph is created</param>
 public CondensationGraphAlgorithm(IVertexListGraph g)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     this.visitedGraph = g;
     this.components   = null;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Uses the dictionary to record the distance
        /// </summary>
        /// <param name="distances">Distance dictionary</param>
        /// <exception cref="ArgumentNullException">distances is null</exception>
        public DistanceRecorderVisitor(VertexIntDictionary distances)
        {
            if (distances == null)
            {
                throw new ArgumentNullException("distances");
            }

            m_Distances = distances;
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="g"></param>
 /// <param name="capacities"></param>
 /// <param name="reversedEdges"></param>
 public PushRelabelMaximumFlowAlgorithm(
     IIndexedVertexListGraph g,
     EdgeDoubleDictionary capacities,
     EdgeEdgeDictionary reversedEdges
     )
     : base(g, capacities, reversedEdges)
 {
     this.visitedGraph = g;
     this.excessFlow   = new VertexDoubleDictionary();
     this.current      = new VertexIntDictionary();
     this.distances    = new VertexIntDictionary();
 }
Ejemplo n.º 12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="g"></param>
 public StrongComponentsAlgorithm(IVertexListGraph g)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     m_VisitedGraph  = g;
     m_Components    = new VertexIntDictionary();
     m_Roots         = new VertexVertexDictionary();
     m_DiscoverTimes = new VertexIntDictionary();
     m_Stack         = new Stack();
     m_Count         = 0;
     m_DfsTime       = 0;
 }
 /// <summary>
 /// Constructs a connected component algorithm, using a component map
 /// </summary>
 /// <param name="g">graph</param>
 /// <param name="components">map where the components are recorded</param>
 /// <exception cref="ArgumentNullException">g or components are null</exception>
 public ConnectedComponentsAlgorithm(IVertexListGraph g,
                                     VertexIntDictionary components)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     if (components == null)
     {
         throw new ArgumentNullException("components");
     }
     this.visitedGraph = g;
     this.components   = components;
 }
Ejemplo n.º 14
0
        internal void ComputeComponents()
        {
            if (components == null)
            {
                components = new VertexIntDictionary();
            }
            //	components is a MAP containing vertex number as key & component_id as value. It maps every vertex in input graph to SCC vertex ID which contains it
            StrongComponentsAlgorithm algo = new StrongComponentsAlgorithm(
                VisitedGraph,
                this.components
                );

            algo.Compute();
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Construct a strong component algorithm
 /// </summary>
 /// <param name="g">graph to apply algorithm on</param>
 /// <exception cref="ArgumentNullException">graph is null</exception>
 public StrongComponentsAlgorithm(IVertexListGraph g)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     this.visitedGraph  = g;
     this.components    = new VertexIntDictionary();
     this.roots         = new VertexVertexDictionary();
     this.discoverTimes = new VertexIntDictionary();
     this.stack         = new Stack();
     this.count         = 0;
     this.dfsTime       = 0;
 }
Ejemplo n.º 16
0
		private bool IsOptimal(MaximumFlowAlgorithm maxFlow)
		{
			// check if mincut is saturated...
			FilteredVertexListGraph residualGraph = new FilteredVertexListGraph(
				maxFlow.VisitedGraph, 
				new ReversedResidualEdgePredicate(maxFlow.ResidualCapacities, maxFlow.ReversedEdges)
				);
			BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(residualGraph);

			VertexIntDictionary distances = new VertexIntDictionary();
			DistanceRecorderVisitor vis = new DistanceRecorderVisitor(distances);
			bfs.RegisterDistanceRecorderHandlers(vis);
			bfs.Compute(sink);

			return distances[source] >= maxFlow.VisitedGraph.VerticesCount;
		}
        public void Init()
        {
            parents       = new VertexVertexDictionary();
            discoverTimes = new VertexIntDictionary();
            finishTimes   = new VertexIntDictionary();
            time          = 0;
            g             = new BidirectionalGraph(true);
            dfs           = new UndirectedDepthFirstSearchAlgorithm(g);

            dfs.StartVertex    += new VertexEventHandler(this.StartVertex);
            dfs.DiscoverVertex += new VertexEventHandler(this.DiscoverVertex);
            dfs.ExamineEdge    += new EdgeEventHandler(this.ExamineEdge);
            dfs.TreeEdge       += new EdgeEventHandler(this.TreeEdge);
            dfs.BackEdge       += new EdgeEventHandler(this.BackEdge);
            dfs.FinishVertex   += new VertexEventHandler(this.FinishVertex);
        }
Ejemplo n.º 18
0
        private void menuItem8_Click(object sender, System.EventArgs e)
        {
            if (this.netronPanel.Graph == null)
            {
                throw new Exception("Generate a graph first");
            }
            if (this.netronPanel.Populator == null)
            {
                throw new Exception("Populator should not be null.");
            }

            ResetVertexAndEdgeColors();

            // create algorithm
            this.vertexCounts = new VertexIntDictionary();
            this.edgeCounts   = new EdgeIntDictionary();
            foreach (IVertex vertex in this.netronPanel.Graph.Vertices)
            {
                this.vertexCounts[vertex] = 0;
            }
            foreach (IEdge edge in this.netronPanel.Graph.Edges)
            {
                this.edgeCounts[edge] = 0;
            }

            this.edgeWeights = new EdgeDoubleDictionary();
            foreach (IEdge edge in this.netronPanel.Graph.Edges)
            {
                edgeWeights[edge] = 1;
            }
            WeightedMarkovEdgeChain chain  = new WeightedMarkovEdgeChain(edgeWeights);
            RandomWalkAlgorithm     walker = new RandomWalkAlgorithm(
                this.netronPanel.Graph
                );

            walker.TreeEdge += new EdgeEventHandler(walker_WeightedTreeEdge);

            LayoutAlgorithmTraverVisitor tracer = new LayoutAlgorithmTraverVisitor(this.netronPanel.Populator);

            walker.TreeEdge += new EdgeEventHandler(tracer.TreeEdge);


            Thread thread = new Thread(new ThreadStart(walker.Generate));

            thread.Start();
        }
        public void Init()
        {
            parents       = new VertexVertexDictionary();
            discoverTimes = new VertexIntDictionary();
            finishTimes   = new VertexIntDictionary();
            time          = 0;
            g             = new AdjacencyGraph(true);
            dfs           = new DepthFirstSearchAlgorithm(g);

            dfs.StartVertex        += new VertexEventHandler(this.StartVertex);
            dfs.DiscoverVertex     += new VertexEventHandler(this.DiscoverVertex);
            dfs.ExamineEdge        += new EdgeEventHandler(this.ExamineEdge);
            dfs.TreeEdge           += new EdgeEventHandler(this.TreeEdge);
            dfs.BackEdge           += new EdgeEventHandler(this.BackEdge);
            dfs.ForwardOrCrossEdge += new EdgeEventHandler(this.FowardOrCrossEdge);
            dfs.FinishVertex       += new VertexEventHandler(this.FinishVertex);
        }
Ejemplo n.º 20
0
 private IVertex FirstNotInChain(ArrayList adj_topo_vertices, VertexIntDictionary vertices_in_a_chain)
 //	Return the first adjacent vertex which is not already present in any of the chains
 {
     if (adj_topo_vertices == null)
     {
         throw new ArgumentNullException("Argument <adj_topo_vertices> in function FirstNotInChain cannot be null");
     }
     if (adj_topo_vertices.Count == 0)
     {
         return(null);
     }
     foreach (IVertex v in adj_topo_vertices)
     {
         if (vertices_in_a_chain[v] == 0)
         {
             return(v);
         }
     }
     return(null);
 }
Ejemplo n.º 21
0
        private ArrayList TopoSortAdjVertices(IVertex v, IIncidenceGraph g, VertexIntDictionary topo_ordering)
        //	return adjacent vertices to "v" sorted in topological order
        {
            IEdgeEnumerator it    = g.OutEdges(v).GetEnumerator();
            bool            valid = false;
            ArrayList       adj   = new ArrayList();

            while (it.MoveNext())
            {
                valid = true;
                adj.Add(it.Current.Target);
            }
            if (!valid)                         // no outgoing edges
            {
                return(adj);
            }
            CompareTopo ctopo = new CompareTopo(topo_ordering);
            SwapTopo    stopo = new SwapTopo();
            QuickSorter qs    = new QuickSorter(ctopo, stopo);

            qs.Sort(adj);
            return(adj);
        }
Ejemplo n.º 22
0
        private SortedList BuildSCCVertexMap(VertexIntDictionary vSccMap)
        {
            //	Construct a map of SCC ID as key & IVertexCollection of vertices contained within the SCC as value
            SortedList       h        = new SortedList();
            VertexCollection vertices = null;

            foreach (DictionaryEntry de in vSccMap)
            {
                IVertex v      = (IVertex)de.Key;
                int     scc_id = (int)de.Value;
                if (h.ContainsKey(scc_id))
                {
                    ((VertexCollection)h[scc_id]).Add(v);
                }
                else
                {
                    vertices = new VertexCollection();
                    vertices.Add(v);
                    h.Add(scc_id, vertices);
                }
            }
            return(h);
        }
Ejemplo n.º 23
0
 public CompareTopo(VertexIntDictionary topological_ordering)
 {
     m_vid = topological_ordering;
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Compute the transitive closure and store it in the supplied graph 'tc'
        /// </summary>
        /// <param name="tc">
        /// Mutable Graph instance to store the transitive closure
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="tc"/> is a <null/>.
        /// </exception>
        public void Create(IMutableVertexAndEdgeListGraph tc)
        {
            if (tc == null)
            {
                throw new ArgumentNullException("tc");
            }
            CondensationGraphAlgorithm cgalgo = new CondensationGraphAlgorithm(VisitedGraph);

            cgalgo.Create(cg);

            ArrayList topo_order          = new ArrayList(cg.VerticesCount);
            TopologicalSortAlgorithm topo = new TopologicalSortAlgorithm(cg, topo_order);

            topo.Compute();

            VertexIntDictionary in_a_chain  = new VertexIntDictionary();
            VertexIntDictionary topo_number = new VertexIntDictionary();

            for (int order = 0; order < topo_order.Count; order++)
            {
                IVertex v = (IVertex)topo_order[order];
                topo_number.Add(v, order);
                if (!in_a_chain.Contains(v))                            // Initially no vertex is present in a chain
                {
                    in_a_chain.Add(v, 0);
                }
            }

            VertexListMatrix chains = new VertexListMatrix();

            int position = -1;

            foreach (IVertex v in topo_order)
            {
                if (in_a_chain[v] == 0)
                {
                    //	Start a new chain
                    position = chains.AddRow();
                    IVertex next = v;
                    for (;;)
                    {
                        chains[position].Add(next);
                        in_a_chain[next] = 1;
                        //	Get adjacent vertices ordered by topological number
                        //	Extend the chain by choosing the adj vertex with lowest topo#
                        ArrayList adj = TopoSortAdjVertices(next, cg, topo_number);
                        if ((next = FirstNotInChain(adj, in_a_chain)) == null)
                        {
                            break;
                        }
                    }
                }
            }

            VertexIntDictionary chain_number = new VertexIntDictionary();
            VertexIntDictionary pos_in_chain = new VertexIntDictionary();

            // Record chain positions of vertices
            SetChainPositions(chains, chain_number, pos_in_chain);

            VertexListMatrix successors = new VertexListMatrix();

            successors.CreateObjectMatrix(cg.VerticesCount, chains.RowCount, int.MaxValue);

            if (topo_order.Count > 0)
            {
                for (int rtopo = topo_order.Count - 1; rtopo > -1; rtopo--)
                {
                    IVertex u = (IVertex)topo_order[rtopo];
                    foreach (IVertex v in TopoSortAdjVertices(u, cg, topo_number))
                    {
                        if (topo_number[v] < (int)successors[u.ID][chain_number[v]])
                        {
                            //	{succ(u)} = {succ(u)} U {succ(v)}
                            LeftUnion(successors[u.ID], successors[v.ID]);
                            //	{succ(u)} = {succ(u)} U {v}
                            successors[u.ID][chain_number[v]] = topo_number[v];
                        }
                    }
                }
            }

            //	Create transitive closure of condensation graph
            //	Remove existing edges in CG & rebuild edges for TC from
            //  successor set (to avoid duplicating parallel edges)
            ArrayList edges = new ArrayList();

            foreach (IEdge e in cg.Edges)
            {
                edges.Add(e);
            }
            foreach (IEdge e in edges)
            {
                cg.RemoveEdge(e);
            }
            foreach (IVertex u in cg.Vertices)
            {
                int i = u.ID;
                for (int j = 0; j < chains.RowCount; j++)
                {
                    int tnumber = (int)successors[i][j];
                    if (tnumber < int.MaxValue)
                    {
                        IVertex v = (IVertex)topo_order[tnumber];
                        for (int k = pos_in_chain[v]; k < chains[j].Count; k++)
                        {
                            cg.AddEdge(u, (IVertex)chains[j][k]);
                        }
                    }
                }
            }

            // Maps a vertex in input graph to it's transitive closure graph
            graphTransitiveClosures = new VertexVertexDictionary();
            //	Add vertices to transitive closure graph
            foreach (IVertex v in visitedGraph.Vertices)
            {
                if (!graphTransitiveClosures.Contains(v))
                {
                    IVertex vTransform = tc.AddVertex();
                    OnInitTransitiveClosureVertex(
                        new TransitiveClosureVertexEventArgs(
                            v, vTransform)
                        );
                    // Fire the TC Vertex Event
                    graphTransitiveClosures.Add(v, vTransform);
                }
            }

            //Add edges connecting vertices within SCC & adjacent
            // SCC (strongly connected component)
            IVertexCollection scc_vertices = null;

            foreach (IVertex s_tccg in cg.Vertices)
            {
                scc_vertices = (IVertexCollection)cgalgo.SCCVerticesMap[s_tccg.ID];
                if (scc_vertices.Count > 1)
                {
                    foreach (IVertex u in scc_vertices)
                    {
                        foreach (IVertex v in scc_vertices)
                        {
                            OnExamineEdge(tc.AddEdge(graphTransitiveClosures[u], graphTransitiveClosures[v]));
                        }
                    }
                }
                foreach (IEdge adj_edge in cg.OutEdges(s_tccg))
                {
                    IVertex t_tccg = adj_edge.Target;
                    foreach (IVertex s in (IVertexCollection)cgalgo.SCCVerticesMap[s_tccg.ID])
                    {
                        foreach (IVertex t in (IVertexCollection)cgalgo.SCCVerticesMap[t_tccg.ID])
                        {
                            OnExamineEdge(tc.AddEdge(graphTransitiveClosures[s], graphTransitiveClosures[t]));
                        }
                    }
                }
            }
        }
 public void Init()
 {
     m_Parents   = new VertexVertexDictionary();
     m_Distances = new VertexIntDictionary();
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public TimeStamperVisitor()
 {
     m_DiscoverTimes = new VertexIntDictionary();
     m_FinishTimes   = new VertexIntDictionary();
     m_Time          = 0;
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public DistanceRecorderVisitor()
 {
     m_Distances = new VertexIntDictionary();
 }