Example #1
0
        public void drawingSequence(Sequence sequence)
        {
            sequence.matrix = getAdjacencyMatrix(sequence.sequence, sequence.length);
            var matrix = sequence.matrix;
            var g      = new AdjacencyGraph <int, Edge <int> >();
            var length = sequence.length;

            for (var i = 1; i <= length; i++)
            {
                g.AddVertex(i);
                for (var j = 0; j < length; j++)
                {
                    if (matrix[i - 1, j] == 1)
                    {
                        matrix[j, i - 1] = 0;
                        var edge = new Edge <int>(i, j + 1);
                        g.AddEdge(edge);
                    }
                }
            }
            var graphViz = new GraphvizAlgorithm <int, Edge <int> >(g, @".\", GraphvizImageType.Png);

            graphViz.FormatVertex += FormatVertex;
            graphViz.FormatEdge   += FormatEdge;
            graphViz.Generate(new FileDotEngine(), sequence.name);

//	        return g;
        }
Example #2
0
		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");
		}
Example #3
0
        /// <summary>
        /// Настроить отображение вершин графа.
        /// </summary>
        /// <param name="graphviz">Объект алгоритма Graphviz для используемого графа.</param>
        /// <param name="dadVertices">Перечисление всех вершин с УСПД в топологии.</param>
        /// <param name="mcdVertices">Перечисление всех вергин с КУ в топологии.</param>
        protected void SetupVerticesFormat(GraphvizAlgorithm <TopologyVertex, TopologyEdge> graphviz,
                                           IEnumerable <TopologyVertex> dadVertices, IEnumerable <TopologyVertex> mcdVertices)
        {
            try
            {
                graphviz.FormatVertex += (sender, args) =>
                {
                    try
                    {
                        // В вершине указываем id участка и координаты внутри участка
                        args.VertexFormatter.Label = args.Vertex.ToString() + "\r\n" + args.Vertex.LaboriousnessWeight;
                        args.VertexFormatter.Group = $"{args.Vertex.Region.Id}_{args.Vertex.RegionY}";      // Группируем участки на графе

                        // Добавить наименование участка к его угловому узлу (заменить в файле на xlabel и добавить forcelabels=true)
                        args.VertexFormatter.ToolTip = (args.Vertex.RegionX == 0 && args.Vertex.RegionY == 0)
                            ? args.Vertex.Region.Name
                            : "";

                        SetVertexColors(args, dadVertices, mcdVertices);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("SetupVerticesFormat failed! {0}", ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine("SetupVerticesFormat failed! {0}", ex.Message);
            }
        }
Example #4
0
        public void Draw(string filename = "HexaGridGraph")
        {
            UndirectedGraph <string, QuickGraph.Edge <string> > mG
                = new UndirectedGraph <string, QuickGraph.Edge <string> >();

            int gridWidth  = _hexes.GetLength(0);
            int gridHeight = _hexes.GetLength(1);

            for (int j = 0; j < gridHeight; j++)
            {
                for (int i = 0; i < gridWidth; i++)
                {
                    mG.AddVertex(_hexes[i, j].GetHexaPos().GetName());
                }
            }

            List <HexaGridEdge> .Enumerator etE = _edgeList.GetEnumerator();
            while (etE.MoveNext())
            {
                QuickGraph.Edge <string> e = new Edge <string>(etE.Current.GetA().GetName(),
                                                               etE.Current.GetB().GetName());
                mG.AddEdge(e);
            }

            var    graphviz    = new GraphvizAlgorithm <string, Edge <string> >(mG);
            string dotFile     = graphviz.Generate(new FileDotEngine(), filename);
            var    diagramFile = dotFile.Replace(".dot", ".png");

            string graphOutput = string.Format(@"""{0}"" -o ""{1}"" -Tpng", dotFile, diagramFile);

            Process.Start(new ProcessStartInfo("dot", graphOutput)
            {
                CreateNoWindow = true, UseShellExecute = false
            });
        }
Example #5
0
        /// <summary>
        ///     Saves the given <see cref="ITreeNode" /> to an image file.
        /// </summary>
        /// <param name="rootNode">The root node of the tree to be saved.</param>
        /// <param name="basePath">The path in which to save the given tree</param>
        /// <param name="fileName">The name of the image file to be saved (without extension)</param>
        /// <param name="formatVertex">The delegate used to format the vertexes.</param>
        /// <param name="formatEdge">The delegate used to format the edges.</param>
        /// <param name="imageType">The type of image file in which to save the tree.</param>
        /// <param name="timeout">The maximum time to wait for Graphviz to create the image file.</param>
        /// <returns>The path to file where the tree image file was saved.</returns>
        public static string ToGraphvizFile(
            this ITreeNode rootNode, string basePath, string fileName,
            FormatVertexEventHandler <Vertex> formatVertex,
            FormatEdgeAction <Vertex, Edge> formatEdge,
            GraphvizImageType imageType = GRAPHVIZ_IMAGE_TYPE, int timeout = GRAPHVIZ_TIMEOUT_MS)
        {
            var graph = new AdjacencyGraph <Vertex, Edge>();

            GraphAdd(rootNode, graph, new Dictionary <ITreeNode, Vertex>());

            var filePath = Path.Combine(basePath, $"{fileName}.dot");

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            var viz = new GraphvizAlgorithm <Vertex, Edge>(graph)
            {
                ImageType = imageType
            };

            if (formatVertex != null)
            {
                viz.FormatVertex += formatVertex;
            }
            if (formatEdge != null)
            {
                viz.FormatEdge += formatEdge;
            }
            return(viz.Generate(new FileDotEngine(timeout), filePath));
        }
Example #6
0
        public void OutputAllMergedActions(
            EdgePredecessorRecorderVisitor erec,
            GraphvizAlgorithm gw,
            string path)
        {
            int i = 1000;

            Console.WriteLine("All paths (merged):");
            foreach (EdgeCollection ec in erec.AllMergedPaths())
            {
                CurrentEdgePath = ec;
                gw.Write(String.Format("path-merged{1}", path, i));
                foreach (IEdge edge in ec)
                {
                    Console.WriteLine("{0}->{1}, {2}",
                                      ((NamedVertex)edge.Source).Name,
                                      ((NamedVertex)edge.Target).Name,
                                      ((NamedEdge)edge).Name
                                      );
                }
                ++i;
                Console.WriteLine();
            }
            CurrentEdgePath = null;
        }
Example #7
0
        /// <summary>
        /// Сгененерировать изображение графа.
        /// </summary>
        /// <param name="map"> НКМ. </param>
        /// <returns> Путь до изображение графа. </returns>
        public string GenerateGraphImage(Core.Models.FuzzyCognitiveMap map)
        {
            var g = new AdjacencyGraph <string, TaggedEdge <string, string> >();

            foreach (var concept in map.Concepts)
            {
                g.AddVertex(concept.Name);
            }

            foreach (var link in map.ConceptsLinks)
            {
                var edge = new TaggedEdge <string, string>(link.From.Name, link.To.Name,
                                                           link.Value.ToString(CultureInfo.InvariantCulture));
                g.AddEdge(edge);
            }

            var graphViz =
                new GraphvizAlgorithm <string, TaggedEdge <string, string> >(g, @".\", GraphvizImageType.Png);

            graphViz.FormatVertex += FormatVertex;
            graphViz.FormatEdge   += FormatEdge;
            var imagePath = graphViz.Generate(new FileDotEngine(), GraphName);

            return(imagePath);
        }
Example #8
0
        /// <summary>
        /// Generates the dot file used for cfg visualization.
        /// </summary>
        /// <param name="filePath">The path to output the CFG dot file.</param>
        public void GenerateDotFile(string filePath)
        {
            var graph = new AdjacencyGraph <CfgNode, Edge <CfgNode> >();

            foreach (var node in Nodes)
            {
                graph.AddVertex(node);
                graph.AddEdgeRange(node.Successors.Select(s => new Edge <CfgNode>(node, s)));
            }

            var graphviz = new GraphvizAlgorithm <CfgNode, Edge <CfgNode> >(graph,
                                                                            filePath,
                                                                            GraphvizImageType.Png);

            graphviz.FormatVertex += FormatVertexEventHandler;
            var output = graphviz.Generate();

            File.WriteAllText(filePath, output);

            void FormatVertexEventHandler(object sender, FormatVertexEventArgs <CfgNode> e)
            {
                e.VertexFormatter.Label   = $"{e.Vertex.Id} {e.Vertex.NodeKind}";
                e.VertexFormatter.ToolTip = e.Vertex.ToString();
            }
        }
Example #9
0
        public void GenerateDotFile()
        {
            var graph = new AdjacencyGraph <string, TaggedEdge <string, string> >();

            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                graph.AddVertex(String.Format("{0}", i));
            }
            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                for (int j = 0; j < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); j++)
                {
                    if ((m_Matrix[i, j] == true) & (i < j))
                    {
                        graph.AddEdge(new TaggedEdge <string, string>(String.Format("{0}", i), String.Format("{0}", j), String.Format("{0}", i)));
                    }
                }
            }

            var graphViz = new GraphvizAlgorithm <string, TaggedEdge <string, string> >(graph, @".\", QuickGraph.Graphviz.Dot.GraphvizImageType.Png);

            graphViz.FormatVertex += (sender, e) =>
            {
                e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Circle;
            };

            graphViz.FormatEdge += (sender, e) =>
            {
                e.EdgeFormatter.Dir = QuickGraph.Graphviz.Dot.GraphvizEdgeDirection.None;
            };

            graphViz.Generate(new FileDotEngine(), m_Name);
        }
Example #10
0
        public void GenerateDotFile()
        {
            var graph = new AdjacencyGraph<string, TaggedEdge<string, string>>();

            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                graph.AddVertex(String.Format("{0}", i));
            }
            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                for (int j = 0; j < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); j++)
                {
                    if ((m_Matrix[i, j] == true) & (i < j))
                    {
                        graph.AddEdge(new TaggedEdge<string, string>(String.Format("{0}", i), String.Format("{0}", j), String.Format("{0}", i)));
                    }
                }
            }

            var graphViz = new GraphvizAlgorithm<string, TaggedEdge<string, string>>(graph, @".\", QuickGraph.Graphviz.Dot.GraphvizImageType.Png);
            graphViz.FormatVertex += (sender, e) =>
            {
                e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Circle;
            };

            graphViz.FormatEdge += (sender, e) =>
            {
                e.EdgeFormatter.Dir = QuickGraph.Graphviz.Dot.GraphvizEdgeDirection.None;
            };

            graphViz.Generate(new FileDotEngine(), m_Name);
        }
        private void InitializeGraph()
        {
            IVertexAndEdgeListGraph <String, Edge <String> > g = this.GDot.VertexNodeList;

            this.Graphviz             = new GraphvizAlgorithm <String, Edge <String> >(g);
            this.Graphviz.FormatEdge += FormatEdge;
        }
Example #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            int N = int.Parse(textBox1.Text);
            int k = int.Parse(textBox5.Text);
            //int iter = N;
            double p = 0.0;

            double.TryParse(textBox2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out p);
            WattsStrogatzModel g = new WattsStrogatzModel(N, false, false, p, k);

            Data.RandomNetwork d = g.Generate();
            if (radioButton4.Checked)
            {
                if (visualize)
                {
                    var    graphviz = new GraphvizAlgorithm <int, UndirectedEdge <int> >(d.MGraph);
                    string output   = graphviz.Generate(new FileDotEngine(), "graph");
                    pictureBox1.ImageLocation = "graph.png";
                }
                label4.Text = string.Format(@"{0}", d.ClusteringCoefficient());
                var degreeDistribuition = d.DegreeDistribuition();


                ErdosDistribuitionDegreeChart.Titles.Add(new Title(RandomGraphStrings.DegreeChartTitle));

                GenerateDegreeDistribuitionChart(chart2, degreeDistribuition);
            }
            if (radioButton3.Checked)
            {
                GenerateAveragePathLengthWattsChart(chart4, N, k);
                GenerateClusteringCoefficientChart(chart3, N, k);
            }
        }
Example #13
0
        private void button2_Click(object sender, EventArgs e)
        {
            int N                 = int.Parse(textBox4.Text);
            int N_init            = int.Parse(textBox6.Text);
            int E                 = int.Parse(textBox3.Text);;
            BarabasiAlbertModel g = new BarabasiAlbertModel(N, false, false, N_init, E);

            Data.RandomNetwork d = g.Generate();
            if (radioButton6.Checked)
            {
                if (visualize)
                {
                    var    graphviz = new GraphvizAlgorithm <int, UndirectedEdge <int> >(d.MGraph);
                    string output   = graphviz.Generate(new FileDotEngine(), "graph");
                    pictureBox2.ImageLocation = "graph.png";
                }
                label4.Text = string.Format(@"{0}", d.ClusteringCoefficient());
                var degreeDistribuition = d.DegreeDistribuition();


                ErdosDistribuitionDegreeChart.Titles.Add(new Title(RandomGraphStrings.DegreeChartTitle));

                GenerateDegreeDistribuitionChart(chart1, degreeDistribuition);
            }
            if (radioButton5.Checked)
            {
                GenerateAveragePathLengthBarabasiChart(chart7, N, N_init, E);
                GenerateClusteringCoefficientChartBarabasi(chart6, N, N_init, E);
            }
        }
Example #14
0
        public void DumpToDot(string fileName)
        {
            var algorithm = new GraphvizAlgorithm <TNode, OperationEdge <TNode> >(this);

            algorithm.FormatEdge += (sender, args) => args.EdgeFormatter.Label.Value = args.Edge.Statement.ToString();
            algorithm.Generate(new FileDotEngine(), fileName);
        }
 public string CreateDotFile()
 {
     var algorithm = new GraphvizAlgorithm<Vertex, Edge<Vertex>>(_graph);
     algorithm.FormatEdge += EdgeStyler;
     algorithm.FormatVertex += VertexStyler;
     return algorithm.Generate();
 }
Example #16
0
        public string CreateDotFile()
        {
            var algorithm = new GraphvizAlgorithm <Vertex, Edge <Vertex> >(_graph);

            algorithm.FormatVertex += VertexStyler;
            return(algorithm.Generate());
        }
Example #17
0
        public void Draw(string filename = "PlanningGraph")
        {
            BidirectionalGraph <string, QuickGraph.Edge <string> > mG
                = new BidirectionalGraph <string, QuickGraph.Edge <string> >();

            for (int t = 0; t < _planningLength; t++)
            {
                List <PlanningNode> .Enumerator eN = _timeLevels[t].mNodes.GetEnumerator();
                while (eN.MoveNext())
                {
                    mG.AddVertex(eN.Current.GetName());
                }
            }

            for (int t = 0; t < _planningLength - 1; t++)
            {
                List <PlanningEdge> .Enumerator eE = _timeLevels[t].mEdges.GetEnumerator();
                while (eE.MoveNext())
                {
                    QuickGraph.Edge <string> e = new Edge <string>(eE.Current.from.GetName(), eE.Current.to.GetName());
                    mG.AddEdge(e);
                }
            }

            var    graphviz    = new GraphvizAlgorithm <string, Edge <string> >(mG);
            string dotFile     = graphviz.Generate(new FileDotEngine(), filename);
            var    diagramFile = dotFile.Replace(".dot", ".png");

            string graphOutput = string.Format(@"""{0}"" -o ""{1}"" -Tpng", dotFile, diagramFile);

            Process.Start(new ProcessStartInfo("dot", graphOutput)
            {
                CreateNoWindow = true, UseShellExecute = false
            });
        }
        private void InitializeGraph()
        {
            IVertexAndEdgeListGraph <String, Edge <String> > g = this.GDot.VertexNodeList;

            this.Graphviz = new GraphvizAlgorithm <String, Edge <String> >(g);
            //this.Graphviz.FormatCluster += Graphviz_FormatCluster;
        }
Example #19
0
        public MaximumFlowDemo()
        {
            graph = new AdjacencyGraph(
                new NamedVertexProvider(),
                new EdgeProvider(),
                true);

            s = (NamedVertex)graph.AddVertex(); s.Name = "s";
            x = (NamedVertex)graph.AddVertex(); x.Name = "x";
            v = (NamedVertex)graph.AddVertex(); v.Name = "v";
            w = (NamedVertex)graph.AddVertex(); w.Name = "w";
            t = (NamedVertex)graph.AddVertex(); t.Name = "t";

            sx = graph.AddEdge(s, x); capacities[sx] = 5;
            sv = graph.AddEdge(s, v); capacities[sv] = 7;
            xv = graph.AddEdge(x, v); capacities[xv] = 3;
            xw = graph.AddEdge(x, w); capacities[xw] = 7;
            wv = graph.AddEdge(w, v); capacities[wv] = 5;
            wt = graph.AddEdge(w, t); capacities[wt] = 4;
            vt = graph.AddEdge(v, t); capacities[vt] = 6;

            this.graphviz           = new GraphvizAlgorithm(this.graph);
            this.graphviz.ImageType = NGraphviz.Helpers.GraphvizImageType.Svg;
            this.graphviz.GraphFormat.RankDirection = NGraphviz.Helpers.GraphvizRankDirection.LR;
            this.graphviz.FormatVertex += new FormatVertexEventHandler(graphviz_FormatVertex);
            this.graphviz.FormatEdge   += new FormatEdgeEventHandler(graphviz_FormatEdge);

            this.reversedEdgeAugmentor = new ReversedEdgeAugmentorAlgorithm(this.graph);
            this.reversedEdgeAugmentor.ReversedEdgeAdded += new EdgeEventHandler(reversedEdgeAugmentor_ReversedEdgeAdded);
        }
Example #20
0
        static void Main(string[] args)
        {
            FASSE fas = new FASSE();
            var edges = new Edge<int>[] { new Edge<int>(0, 1)
                , new Edge<int>(0, 6)
                , new Edge<int>(1, 3)
                , new Edge<int>(2, 0)
                , new Edge<int>(2, 1)
                , new Edge<int>(3, 2)
                , new Edge<int>(3, 4)
                , new Edge<int>(4, 5)
                , new Edge<int>(5, 0)
                , new Edge<int>(5, 6)
                , new Edge<int>(6, 4)
                , new Edge<int>(6, 3)
            };

            GraphGenerator gg = new GraphGenerator();

            BidirectionalGraph<int, Edge<int>> graph = gg.generate(20, 10, 100);//edges.ToBidirectionalGraph<int, Edge<int>>();
            GraphvizAlgorithm<int, Edge<int>> graphviz = new GraphvizAlgorithm<int, Edge<int>>(graph);
            graphviz.Generate(new FileDotEngine(), "g_b");
            List<Edge<int>> mfas = fas.mfas(graph);

            foreach (Edge<int> e in mfas)
            {
                graph.RemoveEdge(e);
            }
            bool f = graph.IsDirectedAcyclicGraph<int, Edge<int>>();
            graphviz.Generate(new FileDotEngine(), "g_a");
            Console.WriteLine(mfas.Count());
        }
Example #21
0
        /// <summary>
        /// Настроить отображение граней графа стандартно с двумя весами каждой грани.
        /// </summary>
        /// <param name="graphviz">Объект алгоритма Graphviz для используемого графа.</param>
        /// <param name="coloredEdges">Перечисление окрашенных путей в графе.</param>
        protected void SetupEdgesFormat(GraphvizAlgorithm <TopologyVertex, TopologyEdge> graphviz, Dictionary <TopologyEdge, Color> coloredEdges)
        {
            try
            {
                graphviz.FormatEdge += (sender, args) =>
                {
                    try
                    {
                        args.EdgeFormatter.Label.Value = args.Edge.ToString();      // Указываем метки граней

                        if (args.Edge.IsAcrossTheBorder())                          // Грани через участки окрашиваем в красный цвет
                        {
                            args.EdgeFormatter.StrokeColor = Color.Red;
                        }

                        if (args.Edge.IsAlongTheBorder())                           // Грани вдоль границ участков окрашиваем в оранжевый цвет
                        {
                            args.EdgeFormatter.StrokeColor = Color.Orange;
                        }

                        HighlightEdge(args, coloredEdges);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("SetupEdgesFormat failed! {0}", ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine("SetupEdgesFormat failed! {0}", ex.Message);
            }
        }
Example #22
0
        public static GraphvizAlgorithm <HeapObject, TEdge> ToLeakGraphviz <TEdge> (this IEdgeListGraph <HeapObject, TEdge> graph, Heapshot heapshot) where TEdge : IEdge <HeapObject>
        {
            var graphviz = new GraphvizAlgorithm <HeapObject, TEdge> (graph);

            graphviz.FormatVertex += (sender, e) => {
                var currentObj = e.Vertex;

                // Look up the object and set its type name.
                var typeName = currentObj.TypeInfo.Name;

                var formatter = e.VertexFormatter;

                e.VertexFormatter.Label = typeName;
                // Append root information.
                if (heapshot.Roots.TryGetValue(currentObj.Address, out var rootRegisterEvent))
                {
                    e.VertexFormatter.Label = $"{typeName}\\nRoot Kind: {rootRegisterEvent.Source.ToString ()}";
                    e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Box;
                }
                else
                {
                    e.VertexFormatter.Label = typeName;
                }
            };

            return(graphviz);
        }
Example #23
0
        public static string ToDotNotation <TVertex, TEdge>(this IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            var viz = new GraphvizAlgorithm <TVertex, TEdge>(graph);

            viz.FormatVertex += VizFormatVertex;
            return(viz.Generate(new DotPrinter(), ""));
        }
Example #24
0
        //TODO: Add [BsonConstructor] to constructors in all entities
        public GridModel(IEdgeListGraph <string, Edge <string> > graph, Dictionary <Edge <string>, double> edgeCost) : base()
        {
            var graphviz = new GraphvizAlgorithm <string, Edge <string> >(graph);

            Dot      = graphviz.Generate();
            Graph    = JsonConvert.SerializeObject(graph);
            EdgeCost = JsonConvert.SerializeObject(edgeCost);
        }
Example #25
0
        // Classificate all edges on three types
        public override string ToString()
        {
            var graphviz = new GraphvizAlgorithm <DominatorTreeNode, Edge <DominatorTreeNode> >(graph);

            graphviz.FormatVertex +=
                (sender, args) => args.VertexFormatter.Label = args.Vertex.CFGNode.Value.Enumerate().First().Label.Value;
            return(graphviz.Generate());
        }
        public void Visualize(string solutionPath)
        {
            Tracer.Info("Vizualizing {0} ...", solutionPath);
            AdjacencyGraph graph = new AdjacencyGraph(new ReferenceVertexProvider(), new EdgeProvider(), false);
            Solution       solution;
            Project        proj = null;

            switch (Path.GetExtension(solutionPath))
            {
            case ".sln":
                solution = Solution.FromFile(solutionPath);
                break;

            case ".csproj":
                solution = Solution.EmptySolution();
                proj     = Project.FromFile(solutionPath, solution);
                proj.Parse();
                solution.Projects.Add(proj.Guid, proj);
                break;

            case ".vbproj":
                solution = Solution.EmptySolution();
                proj     = Project.FromFile(solutionPath, solution);
                proj.Parse();
                solution.Projects.Add(proj.Guid, proj);
                break;

            /*case ".vcproj":
             *  // This is broken, RelativePathToProject is relative from Solution folder
             *  solution = Solution.EmptySolution();
             *  proj = Project.FromVCProjFile(solutionPath);
             *  proj.ParseVCProj();
             *  solution.Projects.Add(proj.Guid, proj);
             *  break;*/
            default:
                MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.UnsupportedExtension, Path.GetExtension(solutionPath)),
                                Resources.DependencyVisualizer, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            GraphvizAlgorithm svg = new GraphvizAlgorithm(graph, Resources.Dependencies, GraphvizImageType.Svg);
            GraphvizAlgorithm png = new GraphvizAlgorithm(graph, Resources.Dependencies, GraphvizImageType.Png);

            foreach (Project project in solution.Projects.Values)
            {
                AddProjectToGraph(project, graph);
            }
            Tracer.Info("Added {0} vertices to graph ...",
                        (graph.VertexProvider as ReferenceVertexProvider).VertexCount);
            svg.WriteVertex += new VertexEventHandler(alg_WriteVertex);
            //svg.Write(Path.GetFileNameWithoutExtension(solutionPath));
            svg.Write(proj.Name);

            png.WriteVertex += new VertexEventHandler(alg_WriteVertex);
            //png.Write(Path.GetFileNameWithoutExtension(solutionPath));
            png.Write(proj.Name);
        }
Example #27
0
        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));
        }
Example #28
0
        public static void PrintGraph(BidirectionalGraph <TVertex, TEdge> graph, string filename)
        {
            var graphViz = new GraphvizAlgorithm <TVertex, TEdge>(graph, @".", QuickGraph.Graphviz.Dot.GraphvizImageType.Png);

            graphViz.FormatVertex += FormatVertex;
            graphViz.FormatEdge   += FormatEdge;
            graphViz.Generate(new FileDotEngine(), filename);
            $"dot -T png {filename} > {filename}.png".Bash();
        }
Example #29
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public GraphvizControl()
 {
     m_Algo = new GraphvizAlgorithm(
         new AdjacencyGraph(true)
         );
     RelativePath     = "";
     m_TimeOut        = new TimeSpan(0, 0, 0, 0, 0);
     m_ImageSize      = new Size(0, 0);
     m_CustomCacheKey = null;
 }
Example #30
0
        public static void OutputUndirectedGraph(IEdgeListGraph<int, TaggedEdge<int, string>> graph, string filename)
        {
            var graphviz = new GraphvizAlgorithm<int, TaggedEdge<int, string>>(graph);

            graphviz.FormatVertex += graphviz_FormatVertex;
            graphviz.FormatEdge += graphviz_FormatEdge;

            graphviz.Generate(new FileDotEngineUndirected(), filename);

            // "C:\Program Files (x86)\Graphviz 2.28\bin\dot.exe" -Tbmp -ograph.bmp graph.dot
        }
Example #31
0
        public void GenerateSameDot()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            // Empty graph
            TestGenerate(graph);

            // Only vertices
            graph.AddVertexRange(new[] { 1, 2 });
            TestGenerate(graph);

            // With edges
            graph.AddVerticesAndEdgeRange(new[]
            {
                new Edge <int>(1, 2),
                new Edge <int>(2, 3),
                new Edge <int>(3, 1)
            });
            TestGenerate(graph);

            // With no cluster
            var clusteredGraph = new ClusteredAdjacencyGraph <int, Edge <int> >(graph);

            TestGenerate(clusteredGraph);

            // With clusters
            ClusteredAdjacencyGraph <int, Edge <int> > subGraph1 = clusteredGraph.AddCluster();

            subGraph1.AddVertexRange(new[] { 4, 5 });
            ClusteredAdjacencyGraph <int, Edge <int> > subGraph2 = clusteredGraph.AddCluster();

            subGraph2.AddVerticesAndEdge(new Edge <int>(1, 6));
            TestGenerate(clusteredGraph);

            #region Local function

            void TestGenerate <TVertex, TEdge>(IEdgeListGraph <TVertex, TEdge> g)
                where TEdge : IEdge <TVertex>
            {
                var    algorithm    = new GraphvizAlgorithm <TVertex, TEdge>(g);
                string generatedDot = algorithm.Generate();

                Assert.IsNotEmpty(generatedDot);

                var dotEngine = new TestDotEngine {
                    ExpectedDot = generatedDot
                };

                // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
                algorithm.Generate(dotEngine, "NotSaved.dot");
            }

            #endregion
        }
Example #32
0
        public static void OutputUndirectedGraph(IEdgeListGraph <int, TaggedEdge <int, string> > graph, string filename)
        {
            var graphviz = new GraphvizAlgorithm <int, TaggedEdge <int, string> >(graph);

            graphviz.FormatVertex += graphviz_FormatVertex;
            graphviz.FormatEdge   += graphviz_FormatEdge;

            graphviz.Generate(new FileDotEngineUndirected(), filename);


            // "C:\Program Files (x86)\Graphviz 2.28\bin\dot.exe" -Tbmp -ograph.bmp graph.dot
        }
        /// <summary>
        /// Output the door dependency graph
        /// </summary>
        /// <param name="filename"></param>
        public void OutputDoorDependencyGraph(string filename)
        {
            var graphviz = new GraphvizAlgorithm<int, Edge<int>>(model.DoorAndClueManager.DoorDependencyGraph);

            graphviz.FormatVertex += graphviz_FormatDoorVertex;

            graphviz.Generate(new FileDotEngine(), filename);

            //TODO: Visualise the full graph, including door and clue locations

            // "C:\Program Files (x86)\Graphviz 2.28\bin\dot.exe" -Tbmp -ograph.bmp graph.dot
        }
Example #34
0
        /// <summary>
        /// Output the door dependency graph
        /// </summary>
        /// <param name="filename"></param>
        public void OutputDoorDependencyGraph(string filename)
        {
            var graphviz = new GraphvizAlgorithm <int, Edge <int> >(model.DoorAndClueManager.DoorDependencyGraph);

            graphviz.FormatVertex += graphviz_FormatDoorVertex;

            graphviz.Generate(new FileDotEngine(), filename);

            //TODO: Visualise the full graph, including door and clue locations

            // "C:\Program Files (x86)\Graphviz 2.28\bin\dot.exe" -Tbmp -ograph.bmp graph.dot
        }
Example #35
0
        public static void Visualize(
            this IVertexAndEdgeListGraph <string, TaggedEdge <string, string> > graph,
            string fileName,
            string dir = @"C:\Temp\AsmSim")
        {
            string fullFileName = Path.Combine(dir, fileName);
            GraphvizAlgorithm <string, TaggedEdge <string, string> > viz = new GraphvizAlgorithm <string, TaggedEdge <string, string> >(graph);

            viz.FormatVertex += VizFormatVertex;
            viz.FormatEdge   += MyEdgeFormatter;
            viz.Generate(new FileDotEngine(), fullFileName);
        }
        /// <summary>
        /// Visualise the full graph, including door and clue locations (though clues will be at the wrapped-up vertex)
        /// </summary>
        /// <param name="filename"></param>
        public void OutputFullGraph(string filename)
        {
            //Visualise the reduced graph, including door and clue locations
            var graphviz = new GraphvizAlgorithm<int, TaggedEdge<int, string>>(model.BaseGraph);

            graphviz.FormatVertex += graphviz_FormatVertex_NoAnnotation;

            graphviz.Generate(new FileDotEngineUndirected(), filename);

            //TODO: Visualise the full graph, including door and clue locations

            // "C:\Program Files (x86)\Graphviz 2.28\bin\dot.exe" -Tbmp -ograph.bmp graph.dot
        }
        public void DrawGraph(string outputFileName)
        {
            var graphviz =
                new GraphvizAlgorithm<Leaf, TaggedEdge<Leaf, string>>(graph);

            graphviz.CommonVertexFormat.Shape = GraphvizVertexShape.Box;
            graphviz.FormatVertex +=
                new FormatVertexEventHandler<Leaf>(graphviz_FormatVertex);
            graphviz.FormatEdge += (sender, e) => {
                e.EdgeFormatter.Label.Value = e.Edge.Tag;
            };
            graphviz.Generate(new FileDotEngine(), outputFileName);
        }
Example #38
0
        private string CreateImageFile(object o, GraphvizImageType imageType, string imageFileName)
        {
            var graph = FactoryProvider.CreateStringGraph();
            FactoryProvider.CreateGraphCreator().Create(o, graph);
            var graphviz = new GraphvizAlgorithm<string, TaggedEdge<string, string>>(graph.ToQuickGraph())
                {
                    ImageType = imageType
                };

            graphviz.FormatVertex += FormatVertexHandler;

            // ReSharper disable AssignNullToNotNullAttribute
            string outputfile = Path.Combine(Path.GetDirectoryName(Environment.CurrentDirectory), imageFileName);
            // ReSharper restore AssignNullToNotNullAttribute

            graphviz.Generate(new FileDotEngine(), outputfile);
            return outputfile;
        }
        private string GenerateDot()
        {
            var graphviz = new GraphvizAlgorithm<int, IEdge<int>>(_graph);
            graphviz.GraphFormat.Size = new Size(100, 100);
            graphviz.GraphFormat.Ratio = GraphvizRatioMode.Auto;
            graphviz.FormatVertex += graphviz_FormatVertex;
            graphviz.FormatEdge += graphviz_FormatEdge;

            foreach (var proc in GraphProcessors)
            {
                proc.PreProcessGraph(graphviz.GraphFormat, _solution);
            }

            string text = graphviz.Generate(new FileDotEngine(), "graph");

            return text;
        }
Example #40
0
        static void PrepareGitHubExample()
        {
            AdjacencyGraph<string, Edge<string>> graph = new AdjacencyGraph<string, Edge<string>>(true);

            // Add some vertices to the graph
            graph.AddVertex("A");
            graph.AddVertex("B");
            graph.AddVertex("C");
            graph.AddVertex("D");
            graph.AddVertex("E");
            graph.AddVertex("F");
            graph.AddVertex("G");
            graph.AddVertex("H");
            graph.AddVertex("I");
            graph.AddVertex("J");

            // Create the edges
            Edge<string> a_b = new Edge<string>("A", "B");
            Edge<string> a_d = new Edge<string>("A", "D");
            Edge<string> b_a = new Edge<string>("B", "A");
            Edge<string> b_c = new Edge<string>("B", "C");
            Edge<string> b_e = new Edge<string>("B", "E");
            Edge<string> c_b = new Edge<string>("C", "B");
            Edge<string> c_f = new Edge<string>("C", "F");
            Edge<string> c_j = new Edge<string>("C", "J");
            Edge<string> d_e = new Edge<string>("D", "E");
            Edge<string> d_g = new Edge<string>("D", "G");
            Edge<string> e_d = new Edge<string>("E", "D");
            Edge<string> e_f = new Edge<string>("E", "F");
            Edge<string> e_h = new Edge<string>("E", "H");
            Edge<string> f_i = new Edge<string>("F", "I");
            Edge<string> f_j = new Edge<string>("F", "J");
            Edge<string> g_d = new Edge<string>("G", "D");
            Edge<string> g_h = new Edge<string>("G", "H");
            Edge<string> h_g = new Edge<string>("H", "G");
            Edge<string> h_i = new Edge<string>("H", "I");
            Edge<string> i_f = new Edge<string>("I", "F");
            Edge<string> i_j = new Edge<string>("I", "J");
            Edge<string> i_h = new Edge<string>("I", "H");
            Edge<string> j_f = new Edge<string>("J", "F");

            // Add the edges
            graph.AddEdge(a_b);
            graph.AddEdge(a_d);
            graph.AddEdge(b_a);
            graph.AddEdge(b_c);
            graph.AddEdge(b_e);
            graph.AddEdge(c_b);
            graph.AddEdge(c_f);
            graph.AddEdge(c_j);
            graph.AddEdge(d_e);
            graph.AddEdge(d_g);
            graph.AddEdge(e_d);
            graph.AddEdge(e_f);
            graph.AddEdge(e_h);
            graph.AddEdge(f_i);
            graph.AddEdge(f_j);
            graph.AddEdge(g_d);
            graph.AddEdge(g_h);
            graph.AddEdge(h_g);
            graph.AddEdge(h_i);
            graph.AddEdge(i_f);
            graph.AddEdge(i_h);
            graph.AddEdge(i_j);
            graph.AddEdge(j_f);

            // Define some weights to the edges
            Dictionary<Edge<string>, double> edgeCost = new Dictionary<Edge<string>, double>(graph.EdgeCount);
            edgeCost.Add(a_b, 4);
            edgeCost.Add(a_d, 1);
            edgeCost.Add(b_a, 74);
            edgeCost.Add(b_c, 2);
            edgeCost.Add(b_e, 12);
            edgeCost.Add(c_b, 12);
            edgeCost.Add(c_f, 74);
            edgeCost.Add(c_j, 12);
            edgeCost.Add(d_e, 32);
            edgeCost.Add(d_g, 22);
            edgeCost.Add(e_d, 66);
            edgeCost.Add(e_f, 76);
            edgeCost.Add(e_h, 33);
            edgeCost.Add(f_i, 11);
            edgeCost.Add(f_j, 21);
            edgeCost.Add(g_d, 12);
            edgeCost.Add(g_h, 10);
            edgeCost.Add(h_g, 2);
            edgeCost.Add(h_i, 72);
            edgeCost.Add(i_f, 31);
            edgeCost.Add(i_h, 18);
            edgeCost.Add(i_j, 7);
            edgeCost.Add(j_f, 8);

            Func<Edge<string>, double> edgeCostFunction = e => edgeCost[e]; // constant cost

            Func<Edge<string>, double> distObserverFunction = e => 1;

            // We want to use Dijkstra on this graph
            DijkstraShortestPathAlgorithm<string, Edge<string>> dijkstra = new DijkstraShortestPathAlgorithm<string, Edge<string>>(graph, edgeCostFunction);

            // attach a distance observer to give us the shortest path distances
            VertexDistanceRecorderObserver<string, Edge<string>> distObserver = new VertexDistanceRecorderObserver<string, Edge<string>>(distObserverFunction);
            distObserver.Attach(dijkstra);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            VertexPredecessorRecorderObserver<string, Edge<string>> predecessorObserver = new VertexPredecessorRecorderObserver<string, Edge<string>>();
            predecessorObserver.Attach(dijkstra);

            // Run the algorithm with A set to be the source
            dijkstra.Compute("A");

            foreach (KeyValuePair<string, double> kvp in distObserver.Distances)
                Console.WriteLine("Distance from root to node {0} is {1}", kvp.Key, kvp.Value);

            foreach (KeyValuePair<string, Edge<string>> kvp in predecessorObserver.VertexPredecessors)
                Console.WriteLine("If you want to get to {0} you have to enter through the in edge {1}", kvp.Key, kvp.Value);

            // Remember to detach the observers
            // distObserver.Detach(dijkstra);
            // predecessorObserver.Detach(dijkstra);

            // Visualize the Graph
            var graphviz = new GraphvizAlgorithm<string, Edge<string>>(graph);
            graphviz.ImageType = GraphvizImageType.Jpeg;

            // render
            string outputString = graphviz.Generate();
            string output = graphviz.Generate(new FileDotEngine(), "MyGraph");
        }
Example #41
0
        static void PrepareMSRDataset()
        {
            AdjacencyGraph<string, Edge<string>> graph = new AdjacencyGraph<string, Edge<string>>(true);
            // Dictionary<Edge<string>, double> edgeCost = new Dictionary<Edge<string>, double>();

            string filePath = @"D:\Debug\ConceptGraph\data-concept\data-concept-instance-relations.txt";
            string line;
            int count = 0;
            using (StreamReader file = new StreamReader(filePath))
            {
                while ((line = file.ReadLine()) != null && count++ <= 20000)
                {
                    string[] tokens = line.Split(new char[] { '\t' });

                    // Add vertices to the graph
                    graph.AddVertex(tokens[0]);
                    graph.AddVertex(tokens[1]);

                    // Create the edges
                    Edge<string> a_b = new Edge<string>(tokens[0], tokens[1]);

                    // Add the edges
                    graph.AddEdge(a_b);

                    // Define weights to the edge
                    // edgeCost.Add(a_b, double.Parse(tokens[2]));
                }
            }

            /*

            Func<Edge<string>, double> edgeCostFunction = e => edgeCost[e]; // constant cost
            Func<Edge<string>, double> distObserverFunction = e => 1;

            // We want to use Dijkstra on this graph
            DijkstraShortestPathAlgorithm<string, Edge<string>> dijkstra = new DijkstraShortestPathAlgorithm<string, Edge<string>>(graph, edgeCostFunction);

            // attach a distance observer to give us the shortest path distances
            VertexDistanceRecorderObserver<string, Edge<string>> distObserver = new VertexDistanceRecorderObserver<string, Edge<string>>(distObserverFunction);
            distObserver.Attach(dijkstra);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            VertexPredecessorRecorderObserver<string, Edge<string>> predecessorObserver = new VertexPredecessorRecorderObserver<string, Edge<string>>();
            predecessorObserver.Attach(dijkstra);

            // Run the algorithm with A set to be the source
            dijkstra.Compute("A");

            foreach (KeyValuePair<string, double> kvp in distObserver.Distances)
                Console.WriteLine("Distance from root to node {0} is {1}", kvp.Key, kvp.Value);

            foreach (KeyValuePair<string, Edge<string>> kvp in predecessorObserver.VertexPredecessors)
                Console.WriteLine("If you want to get to {0} you have to enter through the in edge {1}", kvp.Key, kvp.Value);

            // Remember to detach the observers
            distObserver.Detach(dijkstra);
            predecessorObserver.Detach(dijkstra);

             */

            // Visualize the Graph
            var graphviz = new GraphvizAlgorithm<string, Edge<string>>(graph);
            graphviz.ImageType = GraphvizImageType.Jpeg;

            // render
            string outputString = graphviz.Generate();
            string output = graphviz.Generate(new FileDotEngine(), "MSRConcepts");
        }
Example #42
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            var commandLineArgs = Environment.GetCommandLineArgs();

            if(commandLineArgs.Length < 2)
            {
                PrintHelp();
                return;
            }

            if (commandLineArgs.Contains("-d"))
                Debugger.Launch();

            var asms = from asmLocation in commandLineArgs.Skip(1)
                       where asmLocation != "-d"
                       select AssemblyDefinition.ReadAssembly(asmLocation);

            foreach (var asm in asms)
            {
                AddEdges(asm, 1);
            }

            //var graph = asm.DependencyEdges().ToAdjacencyGraph<AssemblyDefinition, SEdge<AssemblyDefinition>>();
            var graph = _edges.ToAdjacencyGraph<AssemblyDefinition, SEdge<AssemblyDefinition>>();

            var graphviz = new GraphvizAlgorithm<AssemblyDefinition, SEdge<AssemblyDefinition>>(graph);
            graphviz.FormatVertex += (g, args) =>
                                         {
                                             string name = args.Vertex.Name.Name;
                                             args.VertexFormatter.Label = name;
                                             var x = (float)_edgeList[name].Count / _edges.Count * 100;
                                             //args.VertexFormatter
                                             args.VertexFormatter.BottomLabel = _edgeList[name].Count + " edges";
                                         };

            // render

            foreach (var kp in _edgeList.OrderByDescending(f => f.Value.Count))
                Console.Error.WriteLine(kp.Key + ": " + kp.Value.Count);

            Console.Error.WriteLine("Total Dependencies: " + References.Count);
            Console.Error.WriteLine("Total Edges: " + _edges.Count);

            Console.Write(graphviz.Generate());
        }
Example #43
0
        /// <summary>
        /// Makes jpg file with image of graph
        /// </summary>
        /// <param name="automatonName">Name of the automaton to be visualised (InputAutomaton or OutputAutomaton)</param>
        /// <returns></returns>
        public string GetGraph(string automatonName, out AdjacencyGraph<int, TaggedEdge<int, string>> g)
        {
            bool[] visited = new bool[States.Count];
            string[,] matrix = GenerateGraphMatrix(ref visited);

             g = new AdjacencyGraph<int, TaggedEdge<int, string>>(true);
            for (int i = 0; i < States.Count; i++)
            {
                if (visited[i])
                {
                    g.AddVertex(i);
                }
            }

            for (int i = 0; i < States.Count; i++)
                for (int j = 0; j < States.Count; j++)
                {
                    if (matrix[i, j] != "")
                        g.AddEdge(new TaggedEdge<int, string>(i, j, matrix[i, j]));
                }

            GraphvizAlgorithm<int, TaggedEdge<int, string>> graphviz = new GraphvizAlgorithm<int, TaggedEdge<int, string>>(g);
            graphviz.ImageType = GraphvizImageType.Png;
            graphviz.FormatEdge += (sender, args) => { args.EdgeFormatter.Label.Value = args.Edge.Tag.ToString(); };
            string output = graphviz.Generate(new FileDotEngine(), automatonName);

            return output;
        }
Example #44
0
        public void WriteTree()
        {
            BidirectionalGraph<PackageDto, TaggedEdge<PackageDto, EdgeType>> drawgraph =graph.Clone();
            drawgraph.RemoveEdgeIf(x => x.Tag == EdgeType.Affects);
            IVertexAndEdgeListGraph<PackageDto, TaggedEdge<PackageDto, EdgeType>> g = drawgraph;

            var graphviz = new GraphvizAlgorithm<PackageDto, TaggedEdge<PackageDto, EdgeType>>(g);
            graphviz.FormatVertex += graphviz_FormatVertex;
            graphviz.GraphFormat.RankDirection = QuickGraph.Graphviz.Dot.GraphvizRankDirection.LR;
            string test = graphviz.Generate();

            System.IO.File.WriteAllText("test.dot", test);
        }