示例#1
0
		/// <summary>
		/// Create the graph element and stores graph level data.
		/// </summary>
		/// <param name="writer">xml writer</param>
		/// <param name="baseGraph">"base" graph of g</param>
		/// <param name="g">graph to serialize</param>		
		protected override void WriteGraphElem(
			XmlWriter writer,
			ISerializableVertexAndEdgeListGraph baseGraph,
			IVertexAndEdgeListGraph g
			)
		{
			writer.WriteStartElement("gxl");

			// adding xsd ref
			writer.WriteAttributeString("xmlns","http://www.gupro.de/GXL/xmlschema/gxl-1.0.xsd");

			// adding graph node
			writer.WriteStartElement("graph");
			writer.WriteAttributeString("edgeids","true");
			if (g.IsDirected)
				writer.WriteAttributeString("edgemode","directed");
			else
				writer.WriteAttributeString("edgemode","undirected");

			// adding type information
			IGraphSerializationInfo info = new GraphSerializationInfo(true);
			info.Add("graph-type",GetTypeQualifiedName(baseGraph));
			info.Add("vertex-provider-type",GetTypeQualifiedName(baseGraph.VertexProvider));
			info.Add("edge-provider-type",GetTypeQualifiedName(baseGraph.EdgeProvider));
			info.Add("allow-parallel-edges",g.AllowParallelEdges);
			WriteInfo(writer,info);
		}
 public SourceFirstTopologicalSortAlgorithm(
     IVertexAndEdgeListGraph visitedGraph
     )
 {
     this.visitedGraph = visitedGraph;
     this.heap = new PriorithizedVertexBuffer(this.inDegrees);
 }
 public FruchtermanReingoldLayoutAlgorithm(IVertexAndEdgeListGraph graph, SizeF size)
 {
     this.size = size;
     this.graph = graph;
     this.pos = new VertexPointFDictionary();
     this.disp = new VertexVector2DDictionary();
 }
        public void Test(IVertexAndEdgeListGraph g, IVertex root)
        {
            this.root = root;

            RandomWalkAlgorithm walker = new RandomWalkAlgorithm(g);
            walker.TreeEdge +=new EdgeEventHandler(walker_TreeEdge);
            walker.Generate(root,50);

            BidirectionalAdaptorGraph bg = new BidirectionalAdaptorGraph(g);
            ReversedBidirectionalGraph rg = new ReversedBidirectionalGraph(bg);
            CyclePoppingRandomTreeAlgorithm pop = new CyclePoppingRandomTreeAlgorithm(rg);

            pop.InitializeVertex +=new VertexEventHandler(this.InitializeVertex);
            pop.FinishVertex +=new VertexEventHandler(this.FinishVertex);
            pop.TreeEdge += new EdgeEventHandler(this.TreeEdge);

            pop.InitializeVertex +=new VertexEventHandler(vis.InitializeVertex);
            pop.TreeEdge += new EdgeEventHandler(vis.TreeEdge);
            pop.ClearTreeVertex += new VertexEventHandler(vis.ClearTreeVertex);

            pop.RandomTreeWithRoot(root);

            // plot tree...
            GraphvizAlgorithm gv = new GraphvizAlgorithm(g,".",GraphvizImageType.Svg);
            gv.FormatEdge +=new FormatEdgeEventHandler(this.FormatEdge);
            gv.FormatVertex +=new FormatVertexEventHandler(this.FormatVertex);

            gv.Write("randomtree");
        }
 private void CheckVertexCount(IVertexAndEdgeListGraph<string, Edge<string>> g)
 {
     int count = 0;
     foreach (AdjacencyGraph<string, Edge<string>> vertices in this.algo.CondensatedGraph.Vertices)
         count += vertices.VertexCount;
     Assert.AreEqual(g.VertexCount, count, "VertexCount does not match");
 }
        public ChinesePostmanAlgorithm(IVertexAndEdgeListGraph g)
        {
            if (g==null)
                throw new ArgumentNullException("g");

            this.visitedGraph = g;
        }
 public void CondensateAndCheckComponentCount(IVertexAndEdgeListGraph<string, Edge<string>> g)
 {
     this.algo = new CondensationGraphAlgorithm<string, Edge<string>, AdjacencyGraph<string, Edge<string>>>(g);
     this.algo.StronglyConnected = false;
     algo.Compute();
     CheckComponentCount(g);
 }
 /// <summary>
 /// Construct a clustered graph event argument
 /// </summary>
 /// <param name="cluster">cluster to send to event handlers</param>
 /// <param name="graphFormat">cluster formatter</param>
 /// <exception cref="ArgumentNullException">cluster is a null reference.
 /// </exception>
 public FormatClusterEventArgs(IVertexAndEdgeListGraph cluster, GraphvizGraph graphFormat)
 {
     if (cluster==null)
         throw new ArgumentNullException("cluster");
     this.cluster = cluster;
     this.graphFormat = graphFormat;
 }
 public BidirectionalAdaptorGraph(IVertexAndEdgeListGraph g)
 {
     if (g == null)
     {
         throw new ArgumentNullException("grah");
     }
     this.graph = g;
 }
        public void DrawGraph(IVertexAndEdgeListGraph g, string fileName)
        {
            GraphvizAlgorithm gv = new GraphvizAlgorithm(g);
            gv.FormatVertex+=new FormatVertexEventHandler(gv_FormatVertex);
            gv.FormatEdge+=new FormatEdgeEventHandler(gv_FormatEdge);

            System.Diagnostics.Process.Start(gv.Write(fileName));
        }
 /// <summary>
 /// Create a undirected dfs algorithm
 /// </summary>
 /// <param name="g">Graph to search on.</param>
 public UndirectedDepthFirstSearchAlgorithm(IVertexAndEdgeListGraph g)
 {
     if(g == null)
         throw new ArgumentNullException("g");
     m_VisitedGraph = g;
     m_EdgeColors=new EdgeColorDictionary();
     m_Colors = new VertexColorDictionary();
 }
 public LayoutAlgorithm(IVertexAndEdgeListGraph visitedGraph, IVertexPointFDictionary positions)
 {
     this.edgeLength = 20f;
     this.layoutSize = new Size(800, 600);
     this.positions = new VertexPointFDictionary();
     this.computationAbortion = false;
     this.visitedGraph = visitedGraph;
     this.positions = positions;
 }
		/// <summary>
		/// Construct a graph that filters edges and vertices
		/// </summary>
		/// <param name="g">graph to filter</param>
		/// <param name="edgePredicate">edge predicate</param>
		/// <param name="vertexPredicate"></param>
		/// <exception cref="ArgumentNullException">
		/// g or edgePredicate is null
		/// </exception>
		public FilteredVertexAndEdgeListGraph(
			IVertexAndEdgeListGraph g,
			IEdgePredicate edgePredicate,
			IVertexPredicate vertexPredicate
			)
			: base(g,edgePredicate,vertexPredicate)
		{
			this.filteredEdgeList = new FilteredEdgeListGraph(g,edgePredicate);
		}
 public ForceDirectedLayoutAlgorithm(
     IVertexAndEdgeListGraph visitedGraph
     )
     : base(visitedGraph)
 {
     this.preLayoutAlgorithm=new RandomLayoutAlgorithm(visitedGraph,this.Positions);
     this.potential=new DirectedForcePotential(this);
     this.potentials=new VertexPointFDictionary();
 }
 public LargeGraphRenderer()
 {
     this.visitedGraph = null;
     this.positions = new VertexPointFDictionary();
     this.edgeVisible = true;
     this.edgeRenderer = new QuickGraph.Algorithms.Layout.EdgeRenderer();
     this.vertexVisible = true;
     this.vertexRenderer = new QuickGraph.Algorithms.Layout.VertexRenderer();
     this.layoutSize = new Size(800, 600);
 }
 private void CheckEdgeCount(IVertexAndEdgeListGraph<string, Edge<string>> g)
 {
     // check edge count
     int count = 0;
     foreach (CondensatedEdge<string, Edge<string>, AdjacencyGraph<string, Edge<string>>> edges in this.algo.CondensatedGraph.Edges)
         count += edges.Edges.Count;
     foreach (AdjacencyGraph<string, Edge<string>> vertices in this.algo.CondensatedGraph.Vertices)
         count += vertices.EdgeCount;
     Assert.AreEqual(g.EdgeCount, count, "EdgeCount does not match");
 }
示例#17
0
		/// <summary>
		/// Construct an eulerian trail builder
		/// </summary>
		/// <param name="g"></param>
		public EulerianTrailAlgorithm(IVertexAndEdgeListGraph g)
		{
			if (g==null)
				throw new ArgumentNullException("g");
			visitedGraph = g;
			circuit = new EdgeCollection();
			temporaryCircuit = new EdgeCollection();
			currentVertex = null;
			temporaryEdges = new EdgeCollection();
		}
 public static void OutputToDgml(string output, IVertexAndEdgeListGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>> graph)
 {
     graph.ToDirectedGraphML(graph.GetVertexIdentity(), graph.GetEdgeIdentity(), (n, d) =>
         {
             d.Label = n.AssemblyName.Name + " " + n.AssemblyName.Version;
             if (!n.Exists)
                 d.Background = "Red";
             if (!n.Exists && n.Excluded)
                 d.Background = "Yellow";
         }, (e, l) => l.Label = "").WriteXml(output);
 }
 public ForceDirectedLayoutAlgorithm(
     IVertexAndEdgeListGraph visitedGraph,
     IPotential potential,
     ILayoutAlgorithm preLayoutAlgorithm
     )
     : base(visitedGraph)
 {
     this.preLayoutAlgorithm=preLayoutAlgorithm;
     this.potential=potential;
     this.potentials=new VertexPointFDictionary();
 }
        private void Search(IVertexAndEdgeListGraph<string,Edge<string>> g, string root)
        {
            DijkstraShortestPathAlgorithm<string,Edge<string>> algo = new DijkstraShortestPathAlgorithm<string,Edge<string>>(g,
                DijkstraShortestPathAlgorithm<string,Edge<string>>.UnaryWeightsFromEdgeList(g)
                );
            VertexPredecessorRecorderObserver<string,Edge<string>> predecessors = new VertexPredecessorRecorderObserver<string,Edge<string>>();
            predecessors.Attach(algo);
            algo.Compute(root);

            Verify(algo, predecessors);
        }
        public void Compute(IVertexAndEdgeListGraph<string, Edge<string>> g)
        {
            if (g.VertexCount == 0) return;

            var rnd = new Random();
            var distances = new Dictionary<Edge<string>, double>();
            foreach(var edge in g.Edges)
                distances.Add(edge, rnd.Next(100));
            var bfs = new DijkstraShortestPathAlgorithm<string, Edge<string>>(g, distances);

            bfs.Compute(TraversalHelper.GetFirstVertex(g));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="visitedGraph"></param>
        public GraphvizLayout(
            IVertexAndEdgeListGraph visitedGraph,
            VertexSizeFDictionary vertexSizes)
        {
            if (visitedGraph==null)
                throw new ArgumentNullException("visitedGraph");
            if (vertexSizes==null)
                throw new ArgumentNullException("vertexSizes");

            this.visitedGraph = visitedGraph;
            this.vertexSizes = vertexSizes;
        }
        private void CheckDAG(IVertexAndEdgeListGraph<string, Edge<string>> g)
        {
            // check it's a dag
            try
            {
                AlgoUtility.TopologicalSort(this.algo.CondensatedGraph);
            }
            catch (NonAcyclicGraphException)
            {
                Assert.Fail("Graph is not a DAG.");
            }

        }
示例#24
0
        public static IEnumerable <TVertex> SourceFirstTopologicalSort <TVertex, TEdge>(
#if !NET20
            this
#endif
            IVertexAndEdgeListGraph <TVertex, TEdge> visitedGraph)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(visitedGraph != null);

            var vertices = new List <TVertex>(visitedGraph.VertexCount);

            SourceFirstTopologicalSort(visitedGraph, vertices);
            return(vertices);
        }
示例#25
0
        private static void RunWeaklyConnectedCondensateAndCheck <TVertex, TEdge>(
            [NotNull] IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            var algorithm = new CondensationGraphAlgorithm <TVertex, TEdge, AdjacencyGraph <TVertex, TEdge> >(graph)
            {
                StronglyConnected = false
            };

            algorithm.Compute();
            CheckVertexCount(graph, algorithm);
            CheckEdgeCount(graph, algorithm);
            CheckComponentCount(graph, algorithm);
        }
示例#26
0
        public static void OpenAsDGML <TVertex, TEdge>(
            this
            IVertexAndEdgeListGraph <TVertex, TEdge> graph, string filename)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(graph != null);

            if (filename == null)
            {
                filename = "graph.dgml";
            }

            WriteXml(ToDirectedGraphML(graph), filename);
        }
示例#27
0
        public static BidirectionalGraph <TNewVertex, TNewEdge> Convert <TOldVertex, TOldEdge, TNewVertex, TNewEdge>(
            this IVertexAndEdgeListGraph <TOldVertex, TOldEdge> oldGraph,
            Func <TOldVertex, TNewVertex> vertexMapperFunc,
            Func <TOldEdge, TNewEdge> edgeMapperFunc)
            where TOldEdge : IEdge <TOldVertex>
            where TNewEdge : IEdge <TNewVertex>
        {
            Contract.Requires(oldGraph != null);

            return(oldGraph.Convert(
                       new BidirectionalGraph <TNewVertex, TNewEdge>(oldGraph.AllowParallelEdges, oldGraph.VertexCount),
                       vertexMapperFunc,
                       edgeMapperFunc));
        }
示例#28
0
        public static BidirectionalGraph <TVertex, TEdge> CopyToBidirectionalGraph <TVertex, TEdge>(
            this IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(graph != null);
            Contract.Ensures(Contract.Result <BidirectionalGraph <TVertex, TEdge> >() != null);

            var newGraph = new BidirectionalGraph <TVertex, TEdge>();

            //copy the vertices
            newGraph.AddVerticesAndEdgeRange(graph.Edges);

            return(newGraph);
        }
		/// <summary>
		/// Builds a new Bellman Ford searcher.
		/// </summary>
		/// <param name="g">The graph</param>
		/// <param name="weights">Edge weights</param>
		/// <exception cref="ArgumentNullException">Any argument is null</exception>
		/// <remarks>This algorithm uses the <seealso cref="BreadthFirstSearchAlgorithm"/>.</remarks>
		public BellmanFordShortestPathAlgorithm(
			IVertexAndEdgeListGraph g, 
			EdgeDoubleDictionary weights
			)
		{
			if (weights == null)
				throw new ArgumentNullException("Weights");

			m_VisitedGraph = g;
			m_Colors = new VertexColorDictionary();
			m_Weights = weights;
			m_Distances = new VertexDoubleDictionary();
			m_Predecessors = new VertexVertexDictionary();
		}
        public KruskalMinimumSpanningTreeAlgorithm(
            IVertexAndEdgeListGraph visitedGraph,
            EdgeDoubleDictionary weights
            )
        {
            if (visitedGraph==null)
                throw new ArgumentNullException("visitedGraph");
            if (weights==null)
                throw new ArgumentNullException("weights");

            this.visitedGraph = visitedGraph;
            this.weights=weights;
            this.spanningTreeEdges = new EdgeCollection();
        }
        CondensateWeaklyConnected <TVertex, TEdge, TGraph>(
            this IVertexAndEdgeListGraph <TVertex, TEdge> g
            )
            where TEdge : IEdge <TVertex>
            where TGraph : IMutableVertexAndEdgeSet <TVertex, TEdge>, new()
        {
            Contract.Requires(g != null);

            var condensator = new CondensationGraphAlgorithm <TVertex, TEdge, TGraph>(g);

            condensator.StronglyConnected = false;
            condensator.Compute();
            return(condensator.CondensedGraph);
        }
 public FloydWarshallAllShortestPathAlgorithm(IVertexAndEdgeListGraph visitedGraph, IFloydWarshallTester tester)
 {
     if (visitedGraph == null)
     {
         throw new ArgumentNullException("visitedGraph");
     }
     if (tester == null)
     {
         throw new ArgumentNullException("test");
     }
     this.visitedGraph = visitedGraph;
     this.tester = tester;
     this.definedPaths = null;
 }
        /// <summary>
        /// Checks if both graphs <paramref name="g"/> and <paramref name="h"/> are equal.
        /// Use the provided <paramref name="vertexEquality"/> and <paramref name="edgeEquality"/>
        /// comparer to respectively compare vertices and edges.
        /// </summary>
        /// <typeparam name="TVertex">Vertex type.</typeparam>
        /// <typeparam name="TEdge">Edge type.</typeparam>
        /// <param name="g">First graph to compare.</param>
        /// <param name="h">Second graph to compare.</param>
        /// <param name="vertexEquality">Vertex equality comparer.</param>
        /// <param name="edgeEquality">Edge equality comparer.</param>
        /// <returns>True if both graphs are equal, false otherwise.</returns>
        public static bool Equate <TVertex, TEdge>(
            [CanBeNull] IVertexAndEdgeListGraph <TVertex, TEdge> g,
            [CanBeNull] IVertexAndEdgeListGraph <TVertex, TEdge> h,
            [NotNull] IEqualityComparer <TVertex> vertexEquality,
            [NotNull] IEqualityComparer <TEdge> edgeEquality)
            where TEdge : IEdge <TVertex>
        {
            if (g is null)
            {
                return(h is null);
            }
            if (h is null)
            {
                return(false);
            }

            if (ReferenceEquals(g, h))
            {
                return(true);
            }

            if (g.VertexCount != h.VertexCount)
            {
                return(false);
            }

            if (g.EdgeCount != h.EdgeCount)
            {
                return(false);
            }

            foreach (var vertex in g.Vertices)
            {
                if (!h.Vertices.Any(v => vertexEquality.Equals(v, vertex)))
                {
                    return(false);
                }
            }

            foreach (var edge in g.Edges)
            {
                if (!h.Edges.Any(e => edgeEquality.Equals(e, edge)))
                {
                    return(false);
                }
            }

            return(true);
        }
示例#34
0
        private void CheckEdgeCount(IVertexAndEdgeListGraph <string, Edge <string> > g)
        {
            // check edge count
            int count = 0;

            foreach (CondensatedEdge <string, Edge <string>, AdjacencyGraph <string, Edge <string> > > edges in this.algo.CondensatedGraph.Edges)
            {
                count += edges.Edges.Count;
            }
            foreach (AdjacencyGraph <string, Edge <string> > vertices in this.algo.CondensatedGraph.Vertices)
            {
                count += vertices.EdgeCount;
            }
            Assert.AreEqual(g.EdgeCount, count, "EdgeCount does not match");
        }
示例#35
0
        static void Dijkstra <TVertex, TEdge>(
            IVertexAndEdgeListGraph <TVertex, TEdge> g,
            Dictionary <TEdge, double> distances,
            TVertex root)
            where TEdge : IEdge <TVertex>
        {
            var algo = new DijkstraShortestPathAlgorithm <TVertex, TEdge>(
                g,
                AlgorithmExtensions.GetIndexer(distances)
                );
            var predecessors = new VertexPredecessorRecorderObserver <TVertex, TEdge>();

            using (predecessors.Attach(algo))
                algo.Compute(root);
        }
示例#36
0
        public IEnumerable <PrecomputedDijkstraTableRow <TVertex, TEdge> > ComputeRows(
            IVertexAndEdgeListGraph <TVertex, TEdge> graph,
            Func <TEdge, double> cost, Func <TEdge, double> bound, double maxRadius)
        {
            var pquery   = graph.Vertices.AsParallel();
            var allRows  = pquery.SelectMany(rootVertex => this.ComputeRowsSingleSource(graph, rootVertex, cost, bound, maxRadius));
            var rowsList = allRows.ToArray();

            if (this.Logger.IsEnabled(LogLevel.Debug))
            {
                this.Logger.LogDebug("Rows count: {0}", rowsList.Length);
            }

            return(rowsList);
        }
示例#37
0
        /// <summary>
        /// Populates a DGML graph from a graph
        /// </summary>
        /// <typeparam name="TVertex"></typeparam>
        /// <typeparam name="TEdge"></typeparam>
        /// <param name="visitedGraph"></param>
        /// <param name="vertexIdentities"></param>
        /// <param name="edgeIdentities"></param>
        /// <returns></returns>
        public static DirectedGraph ToDirectedGraphML <TVertex, TEdge>(
            this IVertexAndEdgeListGraph <TVertex, TEdge> visitedGraph, VertexIdentity <TVertex> vertexIdentities,
            EdgeIdentity <TVertex, TEdge> edgeIdentities)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(visitedGraph != null);
            Contract.Requires(vertexIdentities != null);
            Contract.Requires(edgeIdentities != null);
            Contract.Ensures(Contract.Result <DirectedGraph>() != null);

            return(ToDirectedGraphML <TVertex, TEdge>(
                       visitedGraph,
                       vertexIdentities,
                       edgeIdentities, null, null));
        }
 /// <summary>
 /// Builds a new Graphviz writer of the graph g using the Stream s.
 /// </summary>
 /// <param name="g">Graph to visit.</param>
 /// <param name="prefix"></param>
 /// <param name="path">Path where files are to be created</param>
 /// <param name="imageType">image output type</param>
 public GraphvizAlgorithm(
     IVertexAndEdgeListGraph g,
     String prefix,
     String path,
     GraphvizImageType imageType
     )
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     m_VisitedGraph = g;
     m_StringWriter = null;
     m_Dot          = new DotRenderer(prefix, path, imageType);
 }
 public LargeGraphRenderer(IVertexAndEdgeListGraph visitedGraph)
 {
     this.visitedGraph = null;
     this.positions = new VertexPointFDictionary();
     this.edgeVisible = true;
     this.edgeRenderer = new QuickGraph.Algorithms.Layout.EdgeRenderer();
     this.vertexVisible = true;
     this.vertexRenderer = new QuickGraph.Algorithms.Layout.VertexRenderer();
     this.layoutSize = new Size(800, 600);
     if (visitedGraph == null)
     {
         throw new ArgumentNullException("visitedGraph");
     }
     this.visitedGraph = visitedGraph;
 }
示例#40
0
        /// <summary>
        /// Wraps a adjacency graph (out-edge only) into a bidirectional graph.
        /// </summary>
        /// <typeparam name="TVertex">type of the vertices</typeparam>
        /// <typeparam name="TEdge">type of the edges</typeparam>
        /// <param name="graph"></param>
        /// <returns></returns>
        public static IBidirectionalGraph <TVertex, TEdge> ToBidirectionalGraph <TVertex, TEdge>
            (this IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(graph != null);

            var self = graph as IBidirectionalGraph <TVertex, TEdge>;

            if (self != null)
            {
                return(self);
            }

            return(new BidirectionAdapterGraph <TVertex, TEdge>(graph));
        }
示例#41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BidirectionalAdapterGraph{TVertex,TEdge}"/> class.
        /// </summary>
        /// <param name="baseGraph">Wrapped bidirectional graph.</param>
        public BidirectionalAdapterGraph([NotNull] IVertexAndEdgeListGraph <TVertex, TEdge> baseGraph)
        {
            _baseGraph = baseGraph ?? throw new ArgumentNullException(nameof(baseGraph));
            _inEdges   = new Dictionary <TVertex, EdgeList <TVertex, TEdge> >(_baseGraph.VertexCount);
            foreach (TEdge edge in _baseGraph.Edges)
            {
                if (!_inEdges.TryGetValue(edge.Target, out EdgeList <TVertex, TEdge> edgeList))
                {
                    edgeList = new EdgeList <TVertex, TEdge>();
                    _inEdges.Add(edge.Target, edgeList);
                }

                edgeList.Add(edge);
            }
        }
示例#42
0
        /// <summary>
        /// Renders action graph
        /// </summary>
        /// <param name="g"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public GraphvizAlgorithm RenderActions(IVertexAndEdgeListGraph g, string path)
        {
            // outputing graph to png
            GraphvizAlgorithm gw = new GraphvizAlgorithm(
                g,                                     // graph to draw
                path,                                  // output file path
                GraphvizImageType.Png                  // output file type
                );

            gw.FormatVertex += new FormatVertexEventHandler(this.FormatVertex);
            gw.FormatEdge   += new FormatEdgeEventHandler(this.FormatEdge);
            gw.Write("actions");

            return(gw);
        }
示例#43
0
        public FloydWarshallAllShortestPathAlgorithm(
            IAlgorithmComponent host,
            IVertexAndEdgeListGraph <TVertex, TEdge> visitedGraph,
            Func <TEdge, double> weights,
            IDistanceRelaxer distanceRelaxer
            )
            : base(host, visitedGraph)
        {
            Contract.Requires(weights != null);
            Contract.Requires(distanceRelaxer != null);

            this.weights         = weights;
            this.distanceRelaxer = distanceRelaxer;
            this.data            = new Dictionary <SEquatableEdge <TVertex>, VertexData>();
        }
 private void CheckDAG <TVertex, TEdge>(
     IVertexAndEdgeListGraph <TVertex, TEdge> g,
     IMutableBidirectionalGraph <AdjacencyGraph <TVertex, TEdge>, CondensedEdge <TVertex, TEdge, AdjacencyGraph <TVertex, TEdge> > > cg)
     where TEdge : IEdge <TVertex>
 {
     // check it's a dag
     try
     {
         cg.TopologicalSort();
     }
     catch (NonAcyclicGraphException)
     {
         Assert.False(true);
     }
 }
示例#45
0
        public static void SourceFirstTopologicalSort <TVertex, TEdge>(
#if !NET20
            this
#endif
            IVertexAndEdgeListGraph <TVertex, TEdge> visitedGraph,
            IList <TVertex> vertices)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(visitedGraph != null);
            Contract.Requires(vertices != null);

            var topo = new SourceFirstTopologicalSortAlgorithm <TVertex, TEdge>(visitedGraph);

            topo.Compute(vertices);
        }
示例#46
0
        public static IMutableBidirectionalGraph <TGraph, CondensatedEdge <TVertex, TEdge, TGraph> > Condensate <TVertex, TEdge, TGraph>(
            IVertexAndEdgeListGraph <TVertex, TEdge> g)
            where TEdge : IEdge <TVertex>
            where TGraph : IMutableVertexAndEdgeListGraph <TVertex, TEdge>, new()
        {
            if (g == null)
            {
                throw new ArgumentNullException("g");
            }

            var condensator = new CondensationGraphAlgorithm <TVertex, TEdge, TGraph>(g);

            condensator.Compute();
            return(condensator.CondensatedGraph);
        }
示例#47
0
        /// <summary>
        /// Wraps a graph (out-edges only) into a bidirectional graph.
        /// </summary>
        /// <remarks>For already bidirectional graph it returns itself.</remarks>
        /// <typeparam name="TVertex">Vertex type.</typeparam>
        /// <typeparam name="TEdge">Edge type.</typeparam>
        /// <param name="graph">Graph to convert.</param>
        /// <returns>A corresponding <see cref="IBidirectionalGraph{TVertex,TEdge}"/>.</returns>


        public static IBidirectionalGraph <TVertex, TEdge> ToBidirectionalGraph <TVertex, TEdge>(
            this IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            if (graph is null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            if (graph is IBidirectionalGraph <TVertex, TEdge> self)
            {
                return(self);
            }

            return(new BidirectionalAdapterGraph <TVertex, TEdge>(graph));
        }
示例#48
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="visitedGraph"></param>
        public GraphvizLayout(
            IVertexAndEdgeListGraph visitedGraph,
            VertexSizeFDictionary vertexSizes)
        {
            if (visitedGraph == null)
            {
                throw new ArgumentNullException("visitedGraph");
            }
            if (vertexSizes == null)
            {
                throw new ArgumentNullException("vertexSizes");
            }

            this.visitedGraph = visitedGraph;
            this.vertexSizes  = vertexSizes;
        }
示例#49
0
        /// <summary>
        /// Populates a DGML graph from a graph
        /// </summary>
        /// <typeparam name="TVertex"></typeparam>
        /// <typeparam name="TEdge"></typeparam>
        /// <param name="visitedGraph"></param>
        /// <returns></returns>
        public static DirectedGraph ToDirectedGraphML <TVertex, TEdge>(
#if !NET20
            this
#endif
            IVertexAndEdgeListGraph <TVertex, TEdge> visitedGraph)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(visitedGraph != null);
            Contract.Ensures(Contract.Result <DirectedGraph>() != null);

            return(ToDirectedGraphML <TVertex, TEdge>(
                       visitedGraph,
                       AlgorithmExtensions.GetVertexIdentity <TVertex>(visitedGraph),
                       AlgorithmExtensions.GetEdgeIdentity <TVertex, TEdge>(visitedGraph)
                       ));
        }
        private static void AssertSameProperties <TVertex, TEdge>(IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            ArrayAdjacencyGraph <TVertex, TEdge> adjacencyGraph = graph.ToArrayAdjacencyGraph();

            Assert.AreEqual(graph.VertexCount, adjacencyGraph.VertexCount);
            CollectionAssert.AreEqual(graph.Vertices, adjacencyGraph.Vertices);

            Assert.AreEqual(graph.EdgeCount, adjacencyGraph.EdgeCount);
            CollectionAssert.AreEqual(graph.Edges, adjacencyGraph.Edges);

            foreach (TVertex vertex in graph.Vertices)
            {
                CollectionAssert.AreEqual(graph.OutEdges(vertex), adjacencyGraph.OutEdges(vertex));
            }
        }
示例#51
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArrayAdjacencyGraph{TVertex,TEdge}"/> class.
        /// </summary>
        /// <param name="visitedGraph">Graph to visit.</param>
        public ArrayAdjacencyGraph([NotNull] IVertexAndEdgeListGraph <TVertex, TEdge> visitedGraph)
        {
            if (visitedGraph is null)
            {
                throw new ArgumentNullException(nameof(visitedGraph));
            }

            _vertexOutEdges = new Dictionary <TVertex, TEdge[]>(visitedGraph.VertexCount);
            EdgeCount       = visitedGraph.EdgeCount;
            foreach (TVertex vertex in visitedGraph.Vertices)
            {
                _vertexOutEdges.Add(
                    vertex,
                    visitedGraph.OutEdges(vertex).ToArray());
            }
        }
示例#52
0
 public static BidirectionalGraph <TNewVertex, TNewEdge> Convert <TOldVertex, TOldEdge, TNewVertex, TNewEdge>(
     [NotNull] this IVertexAndEdgeListGraph <TOldVertex, TOldEdge> oldGraph,
     [CanBeNull, InstantHandle] Func <TOldVertex, TNewVertex> vertexConverter,
     [CanBeNull, InstantHandle] Func <TOldEdge, TNewEdge> edgeConverter)
     where TOldEdge : IEdge <TOldVertex>
     where TNewEdge : IEdge <TNewVertex>
 {
     if (oldGraph is null)
     {
         throw new ArgumentNullException(nameof(oldGraph));
     }
     return(oldGraph.Convert(
                new BidirectionalGraph <TNewVertex, TNewEdge>(oldGraph.AllowParallelEdges, oldGraph.VertexCount),
                vertexConverter,
                edgeConverter));
 }
        public BidirectionAdapterGraph(IVertexAndEdgeListGraph <TVertex, TEdge> baseGraph)
        {
            Contract.Requires(baseGraph != null);

            this.baseGraph = baseGraph;
            this.inEdges   = new Dictionary <TVertex, EdgeList <TVertex, TEdge> >(this.baseGraph.VertexCount);
            foreach (var edge in this.baseGraph.Edges)
            {
                EdgeList <TVertex, TEdge> list;
                if (!this.inEdges.TryGetValue(edge.Target, out list))
                {
                    this.inEdges.Add(edge.Target, list = new EdgeList <TVertex, TEdge>());
                }
                list.Add(edge);
            }
        }
        /// <summary>
        /// Builds a new Bellman Ford searcher.
        /// </summary>
        /// <param name="g">The graph</param>
        /// <param name="weights">Edge weights</param>
        /// <exception cref="ArgumentNullException">Any argument is null</exception>
        /// <remarks>This algorithm uses the <seealso cref="BreadthFirstSearchAlgorithm"/>.</remarks>
        public BellmanFordShortestPathAlgorithm(
            IVertexAndEdgeListGraph g,
            EdgeDoubleDictionary weights
            )
        {
            if (weights == null)
            {
                throw new ArgumentNullException("Weights");
            }

            m_VisitedGraph = g;
            m_Colors       = new VertexColorDictionary();
            m_Weights      = weights;
            m_Distances    = new VertexDoubleDictionary();
            m_Predecessors = new VertexVertexDictionary();
        }
示例#55
0
        public static BidirectionalGraph <TVertex, TEdge> CopyToBidirectionalGraph <TVertex, TEdge>(
            [NotNull] this IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            if (graph is null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            var newGraph = new BidirectionalGraph <TVertex, TEdge>();

            newGraph.AddVertexRange(graph.Vertices);
            newGraph.AddEdgeRange(graph.Edges);

            return(newGraph);
        }
 public ForceDirectedLayoutAlgorithm(IVertexAndEdgeListGraph visitedGraph)
     : base(visitedGraph)
 {
     this.preLayoutAlgorithm = null;
     this.potential = null;
     this.currentIteration = 0;
     this.maxIteration = 500;
     this.potentials = new VertexPointFDictionary();
     this.maxMovement = 50f;
     this.heat = 1f;
     this.heatDecayRate = 0.99f;
     this.syncRoot = null;
     this.preLayoutAlgorithm = new RandomLayoutAlgorithm(visitedGraph, base.Positions);
     this.potential = new DirectedForcePotential(this);
     this.potentials = new VertexPointFDictionary();
 }
 public ForceDirectedLayoutAlgorithm(IVertexAndEdgeListGraph visitedGraph, IPotential potential, ILayoutAlgorithm preLayoutAlgorithm)
     : base(visitedGraph)
 {
     this.preLayoutAlgorithm = null;
     this.potential = null;
     this.currentIteration = 0;
     this.maxIteration = 500;
     this.potentials = new VertexPointFDictionary();
     this.maxMovement = 50f;
     this.heat = 1f;
     this.heatDecayRate = 0.99f;
     this.syncRoot = null;
     this.preLayoutAlgorithm = preLayoutAlgorithm;
     this.potential = potential;
     this.potentials = new VertexPointFDictionary();
 }
示例#58
0
        public void RandomLayoutAlgorithm([NotNull] IVertexAndEdgeListGraph <string, Edge <string> > graph)
        {
            IDictionary <string, Size> verticesSizes = GetVerticesSizes(graph.Vertices);
            var algorithm = new RandomLayoutAlgorithm <string, Edge <string>, IVertexAndEdgeListGraph <string, Edge <string> > >(
                graph,
                verticesSizes,
                null,
                new RandomLayoutParameters())
            {
                Rand = new Random(12345)
            };

            LayoutResults results = ExecuteLayoutAlgorithm(algorithm, verticesSizes, true);

            results.CheckPositions();
        }
示例#59
0
        public static IEnumerable <TEdge> FindShortestPathUndirected <TVertex, TEdge>(
            IVertexAndEdgeListGraph <TVertex, TEdge> graph,
            TVertex startVertex,
            TVertex endVertex)
            where TEdge : class, IEdge <TVertex>
        {
            var undirectedGraph = graph.Edges.ToUndirectedGraph <TVertex, TEdge>();

            if (!(undirectedGraph.Vertices.Any(v => v.Equals(startVertex)) &&
                  undirectedGraph.Vertices.Any(v => v.Equals(endVertex))))
            {
                return(Enumerable.Empty <TEdge>());
            }

            return(FindShortestPath(undirectedGraph, startVertex, endVertex));
        }
示例#60
0
        public RiskResult CalculateMinimalRisk(IVertexAndEdgeListGraph<Station, StationPath> graph, Station from, Station to)
        {
            Func<StationPath, double> calcWeight = visiting => visiting.Risk;
            Func<Station, double> calcHeuristic = visiting => visiting.CalculateRisk(to);

            var algorithm = new AStarShortestPathAlgorithm<Station, StationPath>(graph, calcWeight, calcHeuristic);
            var pathRecorder = new VertexPredecessorRecorderObserver<Station, StationPath>();
            using (pathRecorder.Attach(algorithm))
            {
                algorithm.Compute(from);
                IEnumerable<StationPath> path;
                pathRecorder.TryGetPath(to, out path);

                return new RiskResult(path, from.RadianLocation.Radius);
            }
        }