private void Form1_Load(object sender, EventArgs e) { //create a viewer object Microsoft.Msagl.GraphViewerGdi.GViewer viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer(); //create a graph object Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); //create the graph content //var allServices = ServiceController.GetServices().Where(ser => Services.Contains(ser.ServiceName)); foreach (ServiceController serviceController in ServiceController.GetServices()) { var service = $"{serviceController.DisplayName} ({serviceController.ServiceName})"; graph.AddNode(service); foreach (var dependentService in serviceController.DependentServices) { string dependent = $"{dependentService.DisplayName} ({dependentService.ServiceName})"; graph.AddNode(dependent); graph.AddEdge(dependent, service); } } //bind the graph to the viewer graph.Attr.LayerDirection = LayerDirection.None; graph.Attr.OptimizeLabelPositions = true; graph.CreateLayoutSettings(); graph.LayoutAlgorithmSettings = new MdsLayoutSettings(); viewer.Graph = graph; SuspendLayout(); viewer.Dock = System.Windows.Forms.DockStyle.Fill; Controls.Add(viewer); ResumeLayout(); }
private void VisualizeNodes(IEnumerable <IWeightTensor> sourceNodes, IWeightTensor targetNode) { if (!m_visNeuralNetwork || m_deviceId != 0) { return; } // Create node for target tensor int index = targetNode.Name.LastIndexOf('.'); Microsoft.Msagl.Drawing.Node tgtNode = m_opsViz.AddNode(targetNode.Name); tgtNode.LabelText = targetNode.Name.Substring(index + 1); if (targetNode.IsTrainable) { tgtNode.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightSteelBlue; } if (m_subGraph != null) { // Current compute graph is a sub-graph m_subGraph.AddNode(tgtNode); } // Create edges for each source node and target node foreach (IWeightTensor sourceNode in sourceNodes) { if (!string.IsNullOrEmpty(sourceNode.Name) && !string.IsNullOrEmpty(targetNode.Name)) { string key = $"{sourceNode.Name}->{targetNode.Name}"; if (m_setEdges.Contains(key)) { continue; } int srcIndex = sourceNode.Name.LastIndexOf('.'); Microsoft.Msagl.Drawing.Node srcNode = m_opsViz.AddNode(sourceNode.Name); srcNode.LabelText = sourceNode.Name.Substring(srcIndex + 1); if (sourceNode.IsTrainable) { srcNode.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightSteelBlue; if (m_subGraph != null) { m_subGraph.AddNode(srcNode); } } Edge edge = m_opsViz.AddEdge(sourceNode.Name, targetNode.Name); m_setEdges.Add(key); } } }
static void ProcessLine(Graph graph, string str) { if (String.IsNullOrEmpty(str)) return; if (str[0] == '*') return; var arrayStr = str.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries).ToArray(); if (arrayStr.Length == 0) return; var source = graph.AddNode(arrayStr[0]); for (int i = 1; i < arrayStr.Length; i++) { var e = new Edge(source, graph.AddNode(arrayStr[i]), ConnectionToGraph.Connected); graph.AddPrecalculatedEdge(e); } }
public static Graph AutomatonToDot(BuchiAutomata BA) { Graph g = new Graph("graph"); g.Directed = true; //g.MinNodeWidth = 0; //g.MinNodeHeight = 0; Dictionary <string, string> stateToNumber = new Dictionary <string, string>(); for (int i = 0; i < BA.States.Length; i++) { string state = BA.States[i]; //dot += ("s" + stateToNumber[state] + " [" + (isInitial ? "shape=box" : "") + ((isInitial && isFinal) ? "," : "") + (isFinal ? "style=dotted" : "") + "];\n"); //Node d = g.AddNode("s" + stateToNumber[state.ToString()]); string label = "s" + i; Node d = g.AddNode(label); stateToNumber.Add(state, label); if (BA.InitialStates.Contains(state)) //.isInitial { Node temp = g.AddNode("init-" + label); //temp.Attr.Shape = Shape.InvHouse; temp.Attr.LineWidth = 0; temp.Attr.Color = Color.White; temp.LabelText = ""; g.AddEdge("init-" + label, label); d.Attr.FillColor = Color.Gray; } if (state.EndsWith(Constants.ACCEPT_STATE)) { d.Attr.Shape = Shape.DoubleCircle; //d.Attr.AddStyle(Style.Dotted); } } foreach (Transition transition in BA.Transitions) { //dot += ("s" + stateToNumber[transition.getSourceState()] + " -> " + "s" + stateToNumber[transition.getTargetState()] + " [label=\"" + transition.getLabels() + "\"]" + ";\n"); g.AddEdge(stateToNumber[transition.FromState.ToString()], Ultility.Ultility.PPStringList(transition.labels), stateToNumber[transition.ToState.ToString()]); } return(g); }
public static Graph CreateDrawingGraph(GeometryGraph gg) { counter = 0; localMap = new Dictionary<GeometryNode,Node>(); dg = new Graph(counter++.ToString()) { GeometryGraph = gg }; foreach (GeometryNode n in gg.Nodes) { Node node = new Node(counter++.ToString()); node.Attr.Shape = Shape.Ellipse; node.GeometryNode = n; dg.AddNode(node); localMap[n]=node; } Subgraph cluster = new Subgraph(counter++.ToString()); cluster.GeometryNode = gg.RootCluster; dg.RootSubgraph = cluster; PopulateClusters(cluster, gg.RootCluster); foreach (GeometryEdge e in gg.Edges) { Edge edge = new Edge(localMap[e.Source], localMap[e.Target], ConnectionToGraph.Disconnected); edge.Attr.ArrowheadAtSource = e.ArrowheadAtSource ? ArrowStyle.Normal : ArrowStyle.None; edge.Attr.ArrowheadAtTarget = e.ArrowheadAtTarget ? ArrowStyle.Normal : ArrowStyle.None; edge.GeometryEdge = e; dg.AddPrecalculatedEdge(edge); } //PopulateClusterEdges(dg.RootSubgraph, gg.RootCluster); return dg; }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { Panel.Children.Clear(); var nodes = main.storedata.scenicnode; GraphViewer graphViewer = new GraphViewer(); graphViewer.BindToPanel(Panel); Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph(); foreach (var node in nodes) { if (node.edges.Count == 0) { graph.AddNode(new Node(node.name)); } foreach (var edge in node.edges) { graph.AddEdge(node.name, edge.GetDest(nodes).name); } } //graph.AddEdge("A", "B"); foreach (var node in graph.Nodes) { node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle; node.Attr.Color = Microsoft.Msagl.Drawing.Color.Purple; node.Attr.LabelMargin = 10; } graph.Attr.LayerDirection = LayerDirection.LR; graphViewer.Graph = graph; // throws exception }
private void ModulesGraph() { Graph g = new Graph(); using (SQLiteCommand command = new SQLiteCommand(ConnectionManager.connection)) { command.CommandText = @"select name from modules"; SQLiteDataReader DataReader = command.ExecuteReader(); while (DataReader.Read()) g.AddNode(DataReader["name"].ToString()); } using (SQLiteCommand command = new SQLiteCommand(ConnectionManager.connection)) { command.CommandText = @"select * from moddeps"; SQLiteDataReader DataReader = command.ExecuteReader(); while (DataReader.Read()) { Microsoft.Msagl.Drawing.Edge e = g.AddEdge(DataReader["used"].ToString(), "", DataReader["uses"].ToString()); e.Attr.LineWidth = int.Parse(DataReader["count"].ToString()); //e.Attr.Color = Microsoft.Msagl.Drawing.Color.Yellow; e.LabelText = DataReader["rate"].ToString(); } } gViewer.Graph = g; }
/// <summary> /// Copies a graph and its GeometryGraph. /// </summary> /// <param name="parentGraph"></param> /// <returns></returns> public static Graph CopyGraph(Graph parentGraph) { GeometryGraph geometryCopy = CopyGraph(parentGraph.GeometryGraph); Graph graph=new Graph(); graph.GeometryGraph = geometryCopy; Dictionary<Node,int> nodeId=new Dictionary<Node, int>(geometryCopy.Nodes.Count); for (int i = 0; i < geometryCopy.Nodes.Count; i++) { nodeId[geometryCopy.Nodes[i]] = i; String id = i.ToString(); graph.AddNode(id); var node = graph.FindNode(id); node.GeometryNode = geometryCopy.Nodes[i]; geometryCopy.Nodes[i].UserData = node; } foreach (var edge in geometryCopy.Edges) { String sourceId = nodeId[edge.Source].ToString(); String targetId = nodeId[edge.Target].ToString(); var edgeCopy=graph.AddEdge(sourceId, "", targetId); edgeCopy.GeometryEdge = edge; edge.UserData = edgeCopy; } return graph; }
public virtual void UpdateGraph(Graph graph) { Node graphNode = graph.AddNode(NodeFile.Id); graphNode.LabelText = NodeFile.Name; UpdateGraphNode(graphNode); UpdateOutEdges(graph); }
public GViewer Visualize(int t) { //create a form Form form = new Form(); //create a viewer object GViewer viewer = new GViewer(); //create a graph object Msagl.Graph graph = new Msagl.Graph("Corruption"); //create the graph content foreach (City city in this.cities.Values) { graph.AddNode(city.name); if (city.isInfected) { int red = 255, other = 255; if (city.isInfected) { red = 250; other = 150 - (int)(city.InfectedPercentage(t) * 150); } graph.FindNode(city.name).Attr.FillColor = new Msagl.Color(255, (byte)red, (byte)other, (byte)other); } foreach (City neigh in city.neighbors.Keys) { bool tmp = false; foreach (Edge e in this.infectedEdge) { if ((e.fromCity == city && e.toCity == neigh)) { tmp = true; } } if (!tmp) { graph.AddEdge(city.name, neigh.name).Attr.Color = Msagl.Color.Gray; } } } foreach (Edge e in this.infectedEdge) { graph.AddEdge(e.fromCity.name, e.toCity.name).Attr.Color = Msagl.Color.Red; } //bind the graph to the viewer viewer.Graph = graph; //associate the viewer with the form form.SuspendLayout(); viewer.Dock = DockStyle.Fill; return(viewer); //form.Controls.Add(viewer); //form.ResumeLayout(); //show the form //form.ShowDialog(); }
public AutomatonViewModel() { graph = new Graph(); graph.Attr.LayerDirection = LayerDirection.LR; dummy = new Node(" "); dummy.IsVisible = false; graph.AddNode(dummy); ResetAll(); }
public static Node CreateNode(DiagramNode node) { Node newNode = new Node(node.Name); newNode.Attr.Shape = _figureAdapter.Adapt(node.Type); newNode.Attr.FillColor = _colorAdapter.Adapt(node.FillColor); newNode.Attr.Color = _colorAdapter.Adapt(node.DrawColor); newNode.LabelText = node.Name; _graph.AddNode(newNode); return(newNode); }
static void ReadNode(Graph graph, StreamReader f) { f.ReadLine(); var s=f.ReadLine(); s = s.Trim(' ', '\t', '"'); var id = s.Split(' ')[1]; s = f.ReadLine(); s = s.Trim(' ', '\t', '"'); var split = s.Split(' '); var label = split[1].Trim('"'); graph.AddNode(id).LabelText = label; f.ReadLine(); }
public static void DrawNode(GViewer gLocalViewer, GraphItem item, bool selected, bool maxRelations) { if (gLocalViewer.InvokeRequired) { gLocalViewer.Invoke(new MethodInvoker(delegate() { DrawNode(gLocalViewer, item, selected, maxRelations); })); return; } Microsoft.Msagl.Drawing.Graph graph = gLocalViewer.Graph; Node node = new Node(item.UniqueID); if (item.Name.Length > 12) { node.Label.Text = string.Format("{0}...", item.Name.Substring(0, 6)); } else { node.Label.Text = item.Name; } node.UserData = item; if (selected || maxRelations) { if (selected && maxRelations) { node.DrawNodeDelegate = new DelegateToOverrideNodeRendering(CustomDrawMultiRelaitionsSelectedNode); } else { if (selected) { node.DrawNodeDelegate = new DelegateToOverrideNodeRendering(CustomDrawNormalSelectedNode); } else { if (maxRelations) { node.DrawNodeDelegate = new DelegateToOverrideNodeRendering(CustomDrawMultiRelaitionsNode); } else { node.DrawNodeDelegate = new DelegateToOverrideNodeRendering(CustomDrawNormalNode); } } } } else { node.DrawNodeDelegate = new DelegateToOverrideNodeRendering(CustomDrawNormalNode); } graph.AddNode(node); gLocalViewer.Graph = graph; }
private void ReadNode() { CheckToken(Tokens.Node); XmlRead(); NodeAttr nodeAttr = new NodeAttr(); ReadNodeAttr(nodeAttr); Node node = graph.AddNode(nodeAttr.Id); node.Attr = nodeAttr; ReadLabel(node); ReadEndElement(); }
static void ProcessNodes(DgmlGraph g, Dictionary<string, Subgraph> subgraphTable, Microsoft.Msagl.Drawing.Graph drawingGraph) { foreach (GraphNode gn in g.Nodes) { Node drawingNode; if (subgraphTable.ContainsKey(gn.Id.LiteralValue)) { var subgraph = new Subgraph(gn.Id.LiteralValue); subgraphTable[subgraph.Id] = subgraph; drawingNode = subgraph; } else drawingNode = drawingGraph.AddNode(gn.Id.LiteralValue); drawingNode.Label = new Label(gn.Label) {Owner = drawingNode}; } }
private static void AddSingleNeuron(NeuronViewModelBase root, NeuronViewModelBase selectedNeuron, NeuronViewModelBase value, MsGraph graph) { var n = graph.AddNode(value.NeuronId); n.LabelText = value.Tag; if (selectedNeuron == value) { var mtc = SystemColors.HighlightTextColor; n.Attr.FillColor = NeuronGraphView.GetHighlightColor(); n.Label.FontColor = new Color(mtc.A, mtc.R, mtc.G, mtc.B); } else if (root == value) { n.Attr.Color = NeuronGraphView.GetHighlightColor(); n.Attr.LineWidth *= 1.5; } }
// ----Конструктор /// <summary> /// Конструктор, создающий класс, связывающий SGVL граф с вновь созданным /// соответствующим графом MSAGL /// </summary> /// <param name="graph">SGVL граф, для которого необходим соответствующий MSAGL граф</param> public MsaglGraphWrapper(SgvlGraphs.Graph graph) { SgvlGraph = graph; MsaglGraph = new MsaglGraphs.Graph("graph"); MsaglGraph.Directed = graph.IsDirected; // Создаём вершины графа Msagl foreach (var vertex in graph.Vertices) { var msaglNode = MsaglGraph.AddNode(vertex.Number.ToString()); // Приводим в соответствие значения их атрибутов UpdateMsaglNode(msaglNode, vertex); // Задаём форму в виде круга msaglNode.Attr.Shape = MsaglGraphs.Shape.Circle; // Задаём размер шрифта msaglNode.Label.FontSize = fontSize; // Подписываемся на события изменения атрибутов вершины vertex.LabelChanged += OnVertexLabelChanged; vertex.BorderColorChanged += OnVertexBorderColorChanged; vertex.FillColorChanged += OnVertexFillColorChanged; vertex.BoldChanged += OnVertexBoldChanged; // На изменение координат мы не подписываемся - это пока не работает } // Создаём рёбра графа Msagl foreach (var edge in graph.Edges) { var msaglEdge = MsaglGraph.AddEdge(edge.SourceVertex.Number.ToString(), edge.TargetVertex.Number.ToString()); // Задаём ребру id для быстрого поиска в виде строки msaglEdge.Attr.Id = $"{edge.SourceVertex.Number}-{edge.TargetVertex.Number}"; // Если граф неориентированный, убираем с конца стрелку if (!graph.IsDirected) { msaglEdge.Attr.ArrowheadAtTarget = MsaglGraphs.ArrowStyle.None; } // Приводим в соответствие значения их атрибутов UpdateMsaglEdge(msaglEdge, edge); // Задаём размер шрифта msaglEdge.Label.FontSize = fontSize; // Подписываемся на события изменения атрибутов ребра edge.LabelChanged += OnEdgeLabelChanged; edge.ColorChanged += OnEdgeColorChanged; edge.BoldChanged += OnEdgeBoldChanged; } }
void ReadNodeContent() { XmlRead(); object userData = null; if (TokenIs(Tokens.UserData)) { userData = ReadUserData(); } var nodeAttr = new NodeAttr(); ReadNodeAttr(nodeAttr); var node = graph.AddNode(nodeAttr.Id); node.Label = null; node.Attr = nodeAttr; node.UserData = userData; ReadLabel(node); ReadEndElement(); }
private void PatchGraph(int id) { Graph g = new Graph(); using (SQLiteCommand command = new SQLiteCommand(ConnectionManager.connection)) { command.CommandText = @"select name from modules"; SQLiteDataReader DataReader = command.ExecuteReader(); while (DataReader.Read()) g.AddNode(DataReader["name"].ToString()); } using (SQLiteCommand command = new SQLiteCommand(ConnectionManager.connection)) { command.CommandText = @"select * from patchview where patch_id=@patch_id"; command.Parameters.Add(new SQLiteParameter("@patch_id", id)); SQLiteDataReader DataReader = command.ExecuteReader(); while (DataReader.Read()) { Microsoft.Msagl.Drawing.Edge e = g.AddEdge(DataReader["used"].ToString(), "", DataReader["uses"].ToString()); e.Attr.LineWidth = int.Parse(DataReader["count"].ToString()); e.Attr.Color = Microsoft.Msagl.Drawing.Color.Red; e.LabelText = DataReader["rate"].ToString(); } } using (SQLiteCommand command = new SQLiteCommand(ConnectionManager.connection)) { command.CommandText = @"select * from patchview2 where patch_id=@patch_id"; command.Parameters.Add(new SQLiteParameter("@patch_id", id)); SQLiteDataReader DataReader = command.ExecuteReader(); while (DataReader.Read()) { Microsoft.Msagl.Drawing.Edge e = g.AddEdge(DataReader["used"].ToString(), "", DataReader["uses"].ToString()); e.Attr.LineWidth = int.Parse(DataReader["count"].ToString()); e.Attr.Color = Microsoft.Msagl.Drawing.Color.Yellow; e.LabelText = (int.Parse(DataReader["rate"].ToString())/10).ToString(); } } gViewer.Graph = g; }
public Microsoft.Msagl.Drawing.Graph ConstGraph() { var g = new Microsoft.Msagl.Drawing.Graph(); for (int i = 0; i < Graph.graphEl.Length; i++) { g.AddNode(Graph.graphEl[i]).Attr.FillColor = Color.LightBlue; } bool[,] AdjMx = Graph.graph; for (int i = 0; i < Graph.graphEl.Length; i++) { for (int j = 0; j < Graph.graphEl.Length; j++) { if (AdjMx[i, j]) { g.AddEdge(Graph.graphEl[i], Graph.graphEl[j]); } } } return(g); }
// Returns the last used id private int PopulateGraph(Graph graph, SyntaxWrapper wrapper, int id, string parentId) { // Check if filtering if ((wrapper.GetSyntaxObject() is SyntaxToken && _syntaxTokenCheckBox != null && !_syntaxTokenCheckBox.Checked) || (wrapper.GetSyntaxObject() is SyntaxTrivia && _syntaxTriviaCheckBox != null && !_syntaxTriviaCheckBox.Checked)) { return(id); } // Create the node string nodeId = id.ToString(); Node node = new Node(nodeId); Color color = wrapper.GetColor(); node.Attr.FillColor = new Microsoft.Msagl.Drawing.Color(color.R, color.G, color.B); node.Attr.LabelMargin = 10; node.LabelText = wrapper.GetGraphText(); node.Label.FontColor = Microsoft.Msagl.Drawing.Color.White; node.Label.FontStyle = (Microsoft.Msagl.Drawing.FontStyle)(int) wrapper.GetGraphFontStyle(); graph.AddNode(node); // Add the edge if (parentId != null) { graph.AddEdge(parentId, nodeId); } // Descend IEnumerable children = wrapper.GetChildren(); if (children != null) { // Note that we have to iterate children in reverse order to get them to layout in the correct order foreach (SyntaxWrapper childWrapper in children.Cast <SyntaxWrapper>().Reverse()) { id = PopulateGraph(graph, childWrapper, id + 1, nodeId); } } return(id); }
private void DrawAutoma(AutomaFuzzy.Automa<Symbol> automma) { Graph graph = new Graph("Automa"); //graph.GraphAttr.Backgroundcolor = Microsoft.Glee.Drawing.Color.Black; for (int i = 0; i < automma.States.Count; i++) { string str = automma.States[i].ToString(); Node no = graph.AddNode(automma.States[i].Name); no.Attr.Shape = Shape.Box; no.LabelText = str; } foreach (var transition in automma.Transitions) { string symbol = ((CompilerWithFuzzy.AutomaFuzzy.Rules.SimpleIncludeRule<Symbol>)transition.Rule).Symbol.ToString(); string label = ((CompilerWithFuzzy.AutomaFuzzy.Rules.SimpleIncludeRule<Symbol>)transition.Rule).Symbol.ToString() + " - " + transition.Rule.Pertinence.ToString(); label = symbol; Edge arco = graph.AddEdge(transition.From.Name, label , transition.To.Name); System.Drawing.Color c = Utils.GetColor(transition.Rule.Pertinence); var color = new Microsoft.Msagl.Drawing.Color((byte)c.R, (byte)c.G, (byte)c.B); arco.Attr.Color = color; //arco.Attr.Fontcolor = color; arco.Attr.AddStyle(Style.Bold); arco.Attr.LineWidth = 5; } GViewer viewer = new GViewer(); viewer.NavigationVisible = false; viewer.OutsideAreaBrush = Brushes.White; viewer.ToolBarIsVisible = false; viewer.Graph = graph; viewer.Dock = System.Windows.Forms.DockStyle.Fill; pnlAutoma.Controls.Clear(); pnlAutoma.Controls.Add(viewer); }
public GraphView() { //this.Update(); //this.Controls.Clear(); InitializeComponent(); System.Windows.Forms.Form form = new System.Windows.Forms.Form(); Microsoft.Msagl.GraphViewerGdi.GViewer viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer(); Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); listOfNodes = InputControls.getListOfNodes(); myGraph = InputControls.getMyGraph(); //foreach (var pipe in myGraph.Pipes) //{ // graph.AddEdge(pipe.StartingPoint, pipe.EndPoint); //} var nodeList = new List <Node>(); foreach (var myNode in listOfNodes) { graph.AddNode(new Node(myNode.Name)); } //Microsoft.Msagl.Drawing.Node node = new Microsoft.Msagl.Drawing.Node("a"); //graph.AddEdge("Ali", "Veli"); //graph.AddEdge("B", "C"); //graph.AddEdge("A", "C").Attr.Color = Microsoft.Msagl.Drawing.Color.Green; //graph.FindNode("A").Attr.FillColor = Microsoft.Msagl.Drawing.Color.Magenta; //graph.FindNode("B").Attr.FillColor = Microsoft.Msagl.Drawing.Color.MistyRose; //Microsoft.Msagl.Drawing.Node c = graph.FindNode("C"); //c.Attr.FillColor = Microsoft.Msagl.Drawing.Color.PaleGreen; //c.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Diamond; viewer.Graph = graph; this.SuspendLayout(); viewer.Dock = System.Windows.Forms.DockStyle.Fill; this.Controls.Add(viewer); this.ResumeLayout(); }
private void Draw(Automa<char> automa, int indexTable = -1) { Graph graphAutoma = new Graph("Automa"); for (int i = 0; i < automa.States.Count; i++) { State<char> state = automa.States[i]; Node no = graphAutoma.AddNode(state.Name); no.Attr.Shape = Shape.Circle; if (state.PertinenceFinal > 0) { no.Attr.Shape = Shape.DoubleCircle; } if (indexTable > -1) { System.Drawing.Color c = Utils.GetColor(regexFuzzy.TableAutomaProcessing[indexTable][i]); no.Attr.FillColor = new Microsoft.Msagl.Drawing.Color((byte)c.R, (byte)c.G, (byte)c.B); } else if (state.PertinenceInitial > 0) { no.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGray; } } foreach (var transition in automa.Transitions) { Edge arco = graphAutoma.AddEdge(transition.From.Name, transition.To.Name); arco.LabelText = transition.ToString(); } GViewer viewer = new GViewer(); viewer.NavigationVisible = false; viewer.OutsideAreaBrush = Brushes.White; viewer.ToolBarIsVisible = false; viewer.Graph = graphAutoma; viewer.Dock = System.Windows.Forms.DockStyle.Fill; pnlAutoma.Controls.Clear(); pnlAutoma.Controls.Add(viewer); }
public Graph CreateGraph(List <Edge> edges) { Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph(); foreach (var node in Nodes) { graph.AddNode(node.ID.ToString()).Attr.FillColor = Microsoft.Msagl.Drawing.Color.Yellow; } foreach (var edge in Edges) { var ed = graph.AddEdge(edge.Begin.ID.ToString(), edge.Cost.ToString("#.00"), edge.End.ID.ToString()); if (edges == null) { ed.Attr.Color = Microsoft.Msagl.Drawing.Color.Black; ed.Attr.ArrowheadAtTarget = Microsoft.Msagl.Drawing.ArrowStyle.None; } else { if (edges.Exists(x => x.Color == edge.Color)) { ed.Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } else { ed.Attr.Color = Microsoft.Msagl.Drawing.Color.Black; } ed.Attr.ArrowheadAtTarget = Microsoft.Msagl.Drawing.ArrowStyle.None; } } return(graph); }
private void addNode(Graph g, string label) { g.AddNode(label); g.FindNode(label).UserData = new NodeData(); }
private static void AddNodeToGraph(ref Graph graph, DrawItem drawItem, ref Palette palette, Library.Node snope, ShapeType shapeType) { if (snope.ID == 0) snope.Title = "Finish"; if (Options.Id == (drawItem.Options & Options.Id) && snope.ID != 0) { snope.Title = snope.ID + ": " + snope.Title; } if ((drawItem.Options & Options.Instance) == Options.Instance && snope.ID != 0) snope.Title = String.Format(@"{0} {2}(Instances: {1})", snope.Title, snope.Instances, '\n'); var node = graph.AddNode(snope.ID.ToString()); node.Attr.AddStyle(Style.Bold); node.Label.Text = "\n" + snope.Title + "\n\n"; FormatShapes(node, shapeType); if ((Options.Colour != (drawItem.Options & Options.Colour)) || snope.GroupID == 0) return; var colour = palette.AddColor(snope.GroupID ?? 0, snope.GroupTitle); var groupColour = new Color(colour.Color.R, colour.Color.G, colour.Color.B); node.Attr.FillColor = groupColour; }
private void ViewGraph(Assembly assembly, Type rooType) { var resolver = new DependenciesResolver.DependenciesResolver(assembly); ClassInfo[] classes = rooType == null ? resolver.GetAllClasses().ToArray() : resolver.GetClassesFromRootType(rooType).ToArray(); var graph = new Graph("graph"); foreach (var classInfo in classes) { Type type = classInfo.Type; var rootId = GetNodeId(type); var node = graph.AddNode(rootId); node.LabelText = type.Name; if (type == rooType) { node.Attr.FillColor = Color.PaleGreen; } foreach (var referencedType in classInfo.ReferencedTypes) { graph.AddEdge(rootId, GetNodeId(referencedType)); } } if (SetGraphAction != null) { SetGraphAction(graph); } }
/** Output state label for DOT printing. * @param out the output stream * @param state_index the state index */ public Node formatStateForDOT(int state_index, Graph g) { DA_State cur_state = this.get(state_index); bool has_pos = false, has_neg = false; //std::ostringstream acc_sig; string acc_sig = ""; for (int pair_index = 0; pair_index < this.acceptance().size(); pair_index++) { if (this.acceptance().isStateInAcceptance_L(pair_index, state_index)) { acc_sig += " +" + pair_index; has_pos = true; } if (this.acceptance().isStateInAcceptance_U(pair_index, state_index)) { acc_sig += " -" + pair_index; has_neg = true; } } string label = state_index + "\r\n" +acc_sig.Trim(); //out << "label= \"" << state_index; //if (acc_sig.str().length()!=0) { // out << "\\n" << acc_sig.str(); //} Node d = g.AddNode(label); //if (!has_pos && !has_neg) //{ // //out << ", shape=circle"; // d.Attr.Shape = Shape.DoubleCircle; //} //else //{ // //out << ", shape=box"; // d.Attr.Shape = Shape.Box; //} d.Attr.Shape = Shape.Box; if (this.getStartState() == cur_state) { ////out << ", style=filled, color=black, fillcolor=grey"; //d.Attr.AddStyle(Style.Filled); //d.Attr.Color = Color.Black; //d.Attr.FillColor = Color.Gray; Node temp = g.AddNode("init-" + label); //temp.Attr.Shape = Shape.InvHouse; temp.Attr.LineWidth = 0; temp.Attr.Color = Color.White; temp.LabelText = ""; g.AddEdge("init-" + label, label); d.Attr.FillColor = Color.Gray; } return d; }
//Constructor 3 public FormGraph(int[,] pipeArray) { InitializeComponent(); System.Windows.Forms.Form form = new System.Windows.Forms.Form(); Microsoft.Msagl.GraphViewerGdi.GViewer viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer(); Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); myGraph = InputControls.getMyGraph(); var minCutPipes = new List <MyPipe>(); for (int i = 0; i < myGraph.Pipes.Count(); i++) { //if (MinCut.getNodeNum(myGraph.Pipes[i].StartingPoint) == pipeList[i, 0] // && MinCut.getNodeNum(myGraph.Pipes[i].EndPoint) == pipeList[i, 1]) //{ // minCutPipes.Add(myGraph.Pipes[i]); //} for (int k = 0; k < pipeArray.GetLength(0); k++) { if (MinCut.getNodeNum(myGraph.Pipes[i].StartingPoint) == pipeArray[k, 0] && MinCut.getNodeNum(myGraph.Pipes[i].EndPoint) == pipeArray[k, 1]) { minCutPipes.Add(myGraph.Pipes[i]); } } } var nodeList = new List <Node>(); //node ekle foreach (var myNode in myGraph.Nodes) { graph.AddNode(new Node(myNode.Name)); } //edge ekle foreach (var myPipe in myGraph.Pipes) { if (myPipe.StartingValue != 0) { if (IsMinCutPipe(myPipe, minCutPipes)) { graph.AddEdge(myPipe.StartingPoint, myPipe.StartingValue.ToString(), myPipe.EndPoint).Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } else { graph.AddEdge(myPipe.StartingPoint, myPipe.StartingValue.ToString(), myPipe.EndPoint); } } if (myPipe.EndingValue != 0) { if (true) { graph.AddEdge(myPipe.EndPoint, myPipe.EndingValue.ToString(), myPipe.StartingPoint).Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } else { graph.AddEdge(myPipe.EndPoint, myPipe.EndingValue.ToString(), myPipe.StartingPoint); } } } string startingPointName = myGraph.Nodes.Where(x => x.IsStartingPoint == true) .Select(x => x.Name).FirstOrDefault(); string endPointName = myGraph.Nodes.Where(x => x.IsEndPoint == true) .Select(x => x.Name).FirstOrDefault(); if (startingPointName != null && endPointName != null) { graph.FindNode(startingPointName).Attr.FillColor = Microsoft.Msagl.Drawing.Color.Green; graph.FindNode(startingPointName).Attr.Color = Microsoft.Msagl.Drawing.Color.Green; graph.FindNode(endPointName).Attr.FillColor = Microsoft.Msagl.Drawing.Color.Red; graph.FindNode(endPointName).Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } viewer.Graph = graph; this.SuspendLayout(); viewer.Dock = System.Windows.Forms.DockStyle.Fill; this.Controls.Add(viewer); this.ResumeLayout(); }
public FormGraph() { InitializeComponent(); System.Windows.Forms.Form form = new System.Windows.Forms.Form(); Microsoft.Msagl.GraphViewerGdi.GViewer viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer(); Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); this.Text = "Graph"; myGraph = InputControls.getMyGraph(); var nodeList = new List <Node>(); foreach (var myNode in myGraph.Nodes) { graph.AddNode(new Node(myNode.Name)); } foreach (var myPipe in myGraph.Pipes) { if (myPipe.StartingValue != 0) { graph.AddEdge(myPipe.StartingPoint, myPipe.StartingValue.ToString(), myPipe.EndPoint); } if (myPipe.EndingValue != 0) { graph.AddEdge(myPipe.EndPoint, myPipe.EndingValue.ToString(), myPipe.StartingPoint); } } string startingPointName = myGraph.Nodes.Where(x => x.IsStartingPoint == true) .Select(x => x.Name).FirstOrDefault(); string endPointName = myGraph.Nodes.Where(x => x.IsEndPoint == true) .Select(x => x.Name).FirstOrDefault(); if (startingPointName != null && endPointName != null) { graph.FindNode(startingPointName).Attr.FillColor = Microsoft.Msagl.Drawing.Color.Green; graph.FindNode(startingPointName).Attr.Color = Microsoft.Msagl.Drawing.Color.Green; graph.FindNode(endPointName).Attr.FillColor = Microsoft.Msagl.Drawing.Color.Red; graph.FindNode(endPointName).Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } //Microsoft.Msagl.Drawing.Node node = new Microsoft.Msagl.Drawing.Node("a"); //graph.AddEdge("Ali", "Veli"); //graph.AddEdge("B", "C"); //graph.AddEdge("A", "C").Attr.Color = Microsoft.Msagl.Drawing.Color.Green; //graph.FindNode("A").Attr.FillColor = Microsoft.Msagl.Drawing.Color.Magenta; //graph.FindNode("B").Attr.FillColor = Microsoft.Msagl.Drawing.Color.MistyRose; //Microsoft.Msagl.Drawing.Node c = graph.FindNode("C"); //c.Attr.FillColor = Microsoft.Msagl.Drawing.Color.PaleGreen; //c.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Diamond; viewer.Graph = graph; this.SuspendLayout(); viewer.Dock = System.Windows.Forms.DockStyle.Fill; this.Controls.Add(viewer); this.ResumeLayout(); }
public static void Create_Graph(List<note_node> DTArray) { int index; //String Temp_str = null; System.Windows.Forms.Form GDIForm = new System.Windows.Forms.Form(); GDIForm.Size = new System.Drawing.Size(1000, 1000); //GDIForm.WindowState = FormWindowState.Maximized; //create a viewer object GViewerewer = new Microsoft.Msagl.GraphViewerGdi.GViewer(); //create a graph object Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); //Sort DT Awway by position List<note_node> sorted_list = DTArray.OrderBy(o => o.NoteDetails.position).ToList(); foreach (note_node temp_node in sorted_list) { index = DTArray.IndexOf(temp_node); String Parent_Note; String Current_Note; // Check if it's a route node if (temp_node.parent_node == null) { // Route node so skip Current_Note = temp_node.ToStringSmall() + " Index" + temp_node.tree_index; Node graph_node = new Node(Current_Note); Microsoft.Msagl.Drawing.Color tempcolor = new Microsoft.Msagl.Drawing.Color(); graph_node.Attr.FillColor = Color.AliceBlue; graph_node.Attr.Shape = Shape.Diamond; graph.AddNode(graph_node); } else { //Build the Node string values //Parent_Note = temp_node.parent_node_index.GetValueOrDefault().ToString() + "\r\n" + DTArray[temp_node.parent_node_index.GetValueOrDefault()].ToStringSmall(); ///Current_Note = DTArray.IndexOf(temp_node).ToString() + "\r\n" + temp_node.ToStringSmall(); Parent_Note = temp_node.parent_node.ToStringSmall() + " Index" + temp_node.parent_node.tree_index; Current_Note = temp_node.ToStringSmall() + " Index" + temp_node.tree_index; //Current_Note = temp_node.ToStringSmall(); // 255,0,0 = Red // 0,255,0 = Green // Not route node so add edge details graph.AddEdge(Parent_Note, temp_node.cost.ToString(), Current_Note); //graph.AddNode() //Microsoft.Msagl.Drawing.Color tempcol = Microsoft.Msagl.Drawing.Color. // FromArgb(255,255,255); if (temp_node.Excluded) { graph.FindNode(Current_Note).Attr.FillColor = Color.Red; } } } //bind the graph to the viewer GViewerewer.Graph = graph; //GViewerewer.Size = new System.Drawing.Size(800, 800); //associate the viewer with the GDIForm GDIForm.SuspendLayout(); GViewerewer.Dock = System.Windows.Forms.DockStyle.Fill; GDIForm.Controls.Add(GViewerewer); GDIForm.ResumeLayout(); //show the GDIForm GDIForm.Show(); }
void ShowGraph(bool showMes) { this.groupBoxResult.Controls.Clear(); Microsoft.Msagl.GraphViewerGdi.GViewer viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer(); Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); graph.CreateGeometryGraph(); int i = 1; foreach (var item in lstPoint) { Node node = new Node(i.ToString()); node.Attr.Shape = Shape.Circle; graph.AddNode(node); i++; } graph.FindNode((this.start + 1).ToString()).Attr.FillColor = Color.Blue; graph.FindNode((this.end + 1).ToString()).Attr.FillColor = Color.Red; viewer.Pan(5, 2); for (int j = 0; j < this.soDinh; j++) { for (int k = 0; k < this.soDinh; k++) { if (this.distance[j, k] != this.VOCUNG && this.distance[j, k] != 0) { String tmp = "," + (j + 1).ToString() + "," + (k + 1).ToString() + ","; double dis = Math.Round(this.distance[j, k], 2); if (this.path.Contains(tmp)) { if (this.checkBox.Checked) { graph.AddEdge((j + 1).ToString(), dis.ToString(), (k + 1).ToString()).Attr.Color = Color.Green; } else { graph.AddEdge((j + 1).ToString(), (k + 1).ToString()).Attr.Color = Color.Green; } // Microsoft.Msagl.Core.Layout.Node node = new Microsoft.Msagl.Core.Layout.Node(1, 2); } else { if (this.checkBox.Checked) { graph.AddEdge((j + 1).ToString(), dis.ToString(), (k + 1).ToString()); } else { graph.AddEdge((j + 1).ToString(), (k + 1).ToString()); } } } } } /*graph.AddEdge("A", "C").Attr.Color = Microsoft.Msagl.Drawing.Color.Green; * Edge edge = new Edge("14","sonnx","15"); * * graph.AddEdge("14", "sonnx", "15"); * graph.FindNode("A").Attr.FillColor = Microsoft.Msagl.Drawing.Color.Magenta; * graph.FindNode("B").Attr.FillColor = Microsoft.Msagl.Drawing.Color.MistyRose; * Microsoft.Msagl.Drawing.Node c = graph.FindNode("C"); * c.Attr.FillColor = Microsoft.Msagl.Drawing.Color.PaleGreen; * c.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle;*/ /* * * Microsoft.Msagl.Core.Geometry.Point p1 = new Microsoft.Msagl.Core.Geometry.Point(-497.12352212078628, 1689.84931190121); * Microsoft.Msagl.Core.Geometry.Point p2 = new Microsoft.Msagl.Core.Geometry.Point(198.64235142705752, 2139.4677380013277); * Microsoft.Msagl.Core.Geometry.Point bl = new Microsoft.Msagl.Core.Geometry.Point(-5191.0147700187063, -4395.7850131819132); * double gridSize = 553.23948409846571; * * GridTraversal grid = new GridTraversal(new Rectangle(bl, bl + new Microsoft.Msagl.Core.Geometry.Point(gridSize, gridSize)), 20); * var tiles = grid.GetTilesIntersectedByLineSeg(p1, p2); */ //bind the graph to the viewer viewer.Graph = graph; // viewer.Click += new EventHandler(Group_Click); // viewer.MouseClick += new MouseEventHandler(Group_Click); this.groupBoxResult.SuspendLayout(); viewer.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBoxResult.Controls.Add(viewer); this.groupBoxResult.ResumeLayout(); if (showMes) { if (this.daxet[this.end]) { MessageBox.Show("Độ dài đường đi ngắn nhất " + (Math.Round(d[this.end], 2)).ToString(), "Thành công"); this.txtLoTrinh.Text = this.path; this.txtDoDai.Text = (Math.Round(d[this.end], 2)).ToString(); } else { MessageBox.Show("Không tìm được đường đi ngắn nhất", "Có lỗi xảy ra"); this.txtLoTrinh.Text = ""; this.txtDoDai.Text = ""; } } }
protected override void UpdateOutEdges(Graph graph) { foreach (GameMasterNode node in mArcTriggers.Values) { if (node.NodeType == GameMasterNodeType.ARC) { Node triggerNode = graph.AddNode(NodeFile.Id + "#trigger"); triggerNode.LabelText = "trigger"; MakeNodePrivate(triggerNode); graph.AddEdge(NodeFile.Id, triggerNode.Id); graph.AddEdge(triggerNode.Id, node.Id); } } foreach (GameMasterNode node in mArcChallenges.Values) { if (node.NodeType == GameMasterNodeType.ARC) { Node triggerNode = graph.AddNode(NodeFile.Id + "#challenge"); triggerNode.LabelText = "challenge"; MakeNodePrivate(triggerNode); graph.AddEdge(NodeFile.Id, triggerNode.Id); graph.AddEdge(triggerNode.Id, node.Id); } } foreach (GameMasterNode node in mArcClimaxes.Values) { if (node.NodeType == GameMasterNodeType.ARC) { Node triggerNode = graph.AddNode(NodeFile.Id + "#climax"); triggerNode.LabelText = "climax"; MakeNodePrivate(triggerNode); graph.AddEdge(NodeFile.Id, triggerNode.Id); graph.AddEdge(triggerNode.Id, node.Id); } } }
Graph GetGraph() { var graph = new Graph(); foreach (var graphmlNodePair in _graphmlNodes) { Microsoft.Msagl.Drawing.Node dnode = graph.AddNode(graphmlNodePair.Key); dnode.UserData = graphmlNodePair; if (!string.IsNullOrEmpty(graphmlNodePair.Value.Fullname)) dnode.LabelText = graphmlNodePair.Value.Fullname; } foreach (var graphmlNode in _graphmlNodes.Values) { foreach (var edge in graphmlNode.outEdges) { graph.AddEdge(graphmlNode.Id, edge.Target.Id).UserData = edge; } } return graph; }
private void GenerateMethodsGraph() { foreach (var file in _mainModel.Files.Values) { Color tmpColor = Color.White; if (methodsToFiles) { DrawingNode tmpNode = new DrawingNode(file.Filename); tmpNode.LabelText = file.RelativePath; tmpNode.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Diamond; Color newColor = generateColor(tmpNode.Attr.Color); tmpColor = newColor; tmpNode.Attr.FillColor = tmpColor; if (file.ChangedSinceLastCommit) { tmpNode.LabelText += "[NEW]"; tmpNode.Label.FontStyle = FontStyle.Bold; } graph.AddNode(tmpNode); } foreach (var method in file.Methods) { DrawingNode tmpNode = new DrawingNode(method.Name); tmpNode.LabelText = method.Name + "\nInvokedCount: " + method.InvokedCount + "\nCyclomaticComplexity: " + method.CyclomaticComplexity; tmpNode.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Box; if (!methodsToFiles && method == file.Methods[0]) { Color newColor = generateColor(tmpNode.Attr.Color); tmpColor = newColor; } tmpNode.Attr.FillColor = tmpColor; graph.AddNode(tmpNode); } } if (methodsToNamespaces) { foreach (var namesp in _mainModel.Namespaces.Values) { DrawingNode tmpNode = new DrawingNode(namesp.FullName); tmpNode.LabelText = namesp.FullName + "\nReferencedCount: " + namesp.ReferencedCount; tmpNode.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle; Color newColor = generateColor(tmpNode.Attr.Color); tmpNode.Attr.FillColor = newColor; graph.AddNode(tmpNode); } } foreach (var file in _mainModel.Files.Values) { foreach (var method in file.Methods) { if (methodsToMethods) { foreach (var rMethod in method.MethodRelationsByMethodInvocations.Values) { graph.AddEdge(method.Name, rMethod.ReferencesCount + "", rMethod.Reference.Name); } } if (methodsToNamespaces) { foreach (var namesp in _mainModel.Namespaces.Values) { foreach (var rNamesp in namesp.NamespacesRelationsByMethodReferences.Values) { graph.AddEdge(method.Name, rNamesp.ReferencesCount + "", rNamesp.Reference.FullName); } } } if (methodsToFiles) { graph.AddEdge(method.Name, null, file.Filename); } } } }
static Graph CreateGraphFromTables(Dictionary<string, string> labelDictionary, List<Tuple<string, string>> edgeList) { var graph=new Graph(); graph.LayoutAlgorithmSettings = new MdsLayoutSettings(); foreach (var v in labelDictionary.Values) graph.AddNode(v); foreach (var tuple in edgeList) { var e=graph.AddEdge(labelDictionary[tuple.Item1], labelDictionary[tuple.Item2]); } return graph; }
private async void OnStartClick(object sender, RoutedEventArgs e) { _processedFiles.Clear(); _dependencies.Clear(); if (string.IsNullOrWhiteSpace(txtPath.Text)) { MessageBox.Show(this, "Please select a file", "MSBuild Dependency Visualizer", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } var controller = await this.ShowProgressAsync("Please wait...", "Processing files.."); try { await TraverseProjects(txtPath.Text, true); _graph = new Graph(); double i = 1.0; foreach (KeyValuePair<string, List<string>> item in _dependencies) { double percent = i / _dependencies.Count; controller.SetProgress(percent); controller.SetMessage($"Processing... {item.Key}"); await Task.Delay(50); var node = _graph.AddNode(item.Key); node.Attr.FillColor = Color.LightGreen; foreach (var child in item.Value) { var edge = _graph.AddEdge(node.LabelText, child); } i += 1.0; } _graph.Attr.LayerDirection = LayerDirection.LR; _graphViewer.Graph = _graph; await controller.CloseAsync(); } catch (Exception exception) { await controller.CloseAsync(); await this.ShowMessageAsync("Oops! Error occurred", exception.Message); } }
//maxFlowPath => { "A", "B", "C", "E" } //Constructor 2 public FormGraph(List <string> maxFlowPath, bool isMaxFlowPath) { //this.Text = flow.ToString(); List <string[]> binaryList = new List <string[]>(); InitializeComponent(); System.Windows.Forms.Form form = new System.Windows.Forms.Form(); Microsoft.Msagl.GraphViewerGdi.GViewer viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer(); Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); //listOfNodes = InputControls.getListOfNodes(); myGraph = InputControls.getMyGraph(); var nodeList = new List <Node>(); //node ekle foreach (var myNode in myGraph.Nodes) { graph.AddNode(new Node(myNode.Name)); } List <List <string> > binaryPaths = new List <List <string> >(); for (int i = 0; i < maxFlowPath.Count() - 1; i++) { binaryPaths.Add(new List <string> { maxFlowPath[i], maxFlowPath[i + 1] }); } //edge ekle foreach (var myPipe in myGraph.Pipes) { if (myPipe.StartingValue != 0) { if (IsOnThePath(myPipe, binaryPaths)) { if (isMaxFlowPath) { graph.AddEdge(myPipe.StartingPoint, myPipe.StartingValue.ToString(), myPipe.EndPoint).Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } else { graph.AddEdge(myPipe.StartingPoint, myPipe.StartingValue.ToString(), myPipe.EndPoint).Attr.Color = Microsoft.Msagl.Drawing.Color.Blue; } } else { graph.AddEdge(myPipe.StartingPoint, myPipe.StartingValue.ToString(), myPipe.EndPoint); } } if (myPipe.EndingValue != 0) { if (IsOnThePath(myPipe, binaryPaths)) { if (isMaxFlowPath) { graph.AddEdge(myPipe.EndPoint, myPipe.EndingValue.ToString(), myPipe.StartingPoint).Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } else { graph.AddEdge(myPipe.EndPoint, myPipe.EndingValue.ToString(), myPipe.StartingPoint).Attr.Color = Microsoft.Msagl.Drawing.Color.Blue; } } else { graph.AddEdge(myPipe.EndPoint, myPipe.EndingValue.ToString(), myPipe.StartingPoint); } } } string startingPointName = myGraph.Nodes.Where(x => x.IsStartingPoint == true) .Select(x => x.Name).FirstOrDefault(); string endPointName = myGraph.Nodes.Where(x => x.IsEndPoint == true) .Select(x => x.Name).FirstOrDefault(); if (startingPointName != null && endPointName != null) { graph.FindNode(startingPointName).Attr.FillColor = Microsoft.Msagl.Drawing.Color.Green; graph.FindNode(startingPointName).Attr.Color = Microsoft.Msagl.Drawing.Color.Green; graph.FindNode(endPointName).Attr.FillColor = Microsoft.Msagl.Drawing.Color.Red; graph.FindNode(endPointName).Attr.Color = Microsoft.Msagl.Drawing.Color.Red; } viewer.Graph = graph; this.SuspendLayout(); viewer.Dock = System.Windows.Forms.DockStyle.Fill; this.Controls.Add(viewer); this.ResumeLayout(); }
public void DrawChart(Microsoft.Msagl.GraphViewerGdi.GViewer gViewer, Population population) { //gViewer1.NeedToCalculateLayout = false; //create a graph object Microsoft.Msagl.Drawing.Graph graph = new Microsoft.Msagl.Drawing.Graph("graph"); //create the graph content foreach (var chromosome in population.chromosomes) { graph.AddNode("p" + chromosome.id.ToString()); foreach (var edge in population.GetEdges()) { Node n = graph.AddNode(chromosome.id.ToString() + edge.Key.ToString()); n.LabelText = edge.Key.ToString(); n = graph.AddNode(chromosome.id.ToString() + edge.Value.ToString()); n.LabelText = edge.Value.ToString(); graph.AddEdge(chromosome.id.ToString() + edge.Key.ToString(), chromosome.id.ToString() + edge.Value.ToString()); } } foreach (var edge in graph.Edges) { edge.Attr.ArrowheadAtTarget = ArrowStyle.None; } foreach (var node in graph.Nodes) { if (node.Id.StartsWith("p")) { node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Plaintext; } else { node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle; } } /*graph.FindNode("A").Attr.FillColor = Microsoft.Msagl.Drawing.Color.Magenta; * graph.FindNode("B").Attr.FillColor = Microsoft.Msagl.Drawing.Color.MistyRose; * Microsoft.Msagl.Drawing.Node c = graph.FindNode("C"); * c.Attr.FillColor = Microsoft.Msagl.Drawing.Color.PaleGreen; * c.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Diamond;*/ //bind the graph to the viewer //graph.LayerConstraints.AddSameLayerNeighbors(graph.FindNode("1"), graph.FindNode("2"), graph.FindNode("3"), graph.FindNode("4"), graph.FindNode("5")); foreach (var chromosome in population.chromosomes) { List <Node> nl = new List <Node>(); nl.Add(Dn(graph, "p" + chromosome.id.ToString())); foreach (var gene in chromosome.genes) { nl.Add(Dn(graph, chromosome.id.ToString() + gene)); } graph.LayerConstraints.AddSameLayerNeighbors(nl); } //graph.LayerConstraints.AddSameLayerNeighbors(Dn(graph, "11"), Dn(graph, "12"), Dn(graph, "13"), Dn(graph, "14"), Dn(graph, "15")); //graph.LayerConstraints.AddSameLayerNeighbors(Dn(graph, "21"), Dn(graph, "22"), Dn(graph, "23"), Dn(graph, "24"), Dn(graph, "25")); //graph.LayerConstraints.AddSameLayerNeighbors(Dn(graph, "31"), Dn(graph, "32"), Dn(graph, "33"), Dn(graph, "34"), Dn(graph, "35")); List <Node> cst = new List <Node>(); foreach (var chromosome in population.chromosomes) { cst.Add(Dn(graph, chromosome.id.ToString() + chromosome.genes[0].ToString())); } for (var i = 0; i < cst.Count - 1; i++) { graph.LayerConstraints.AddUpDownConstraint(cst[i], cst[i + 1]); } //graph.LayerConstraints.AddUpDownConstraint(Dn(graph, "11"), Dn(graph, "22")); //graph.LayerConstraints.AddUpDownConstraint(Dn(graph, "22"), Dn(graph, "35")); gViewer.Graph = graph; }
static Node AddSchemaBox(Hashtable table, string uri, Graph g) { Node b1; if (table.ContainsKey(uri)) { b1 = (Node) table[uri]; } else { // Make sure labels are unique. string baseLabel = GetFileName(uri); string label = baseLabel; int count = 0; Node found = g.FindNode(baseLabel); while (found != null) { count++; label = baseLabel + "(" + count + ")"; found = g.FindNode(label); } b1 = g.AddNode(uri); SetNodeColors(b1); b1.Attr.Shape = Shape.Box; b1.LabelText = label; b1.Attr.XRadius = b1.Attr.YRadius = 2; // rounded box. b1.Attr.LabelMargin = 5; table[uri] = b1; } return b1; }
/// <summary> /// Desenha o autômato. /// </summary> private void Desenha(StackAutoma automato) { Graph grafoAutomato = new Graph("Autômato"); transicoes = new List<Transition>(); // Adiciona elementos com base nas transições foreach (KeyValuePair<string, State> estado in automato.States) { Node no = grafoAutomato.AddNode(estado.Key); no.Attr.Shape = Shape.Circle; // Faz marcações no grafo.. if (estado.Value.Final) { no.Attr.Shape = Shape.DoubleCircle; } if (estado.Value == automato.StartState) { no.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGray; } transicoes.AddRange(estado.Value.Transitions); } foreach (Transition transicao in transicoes) { Edge arco = grafoAutomato.AddEdge(transicao.Source.Name, transicao.Destiny.Name); arco.LabelText = string.Format("({0}, {1}, {{{2}}})", transicao.Symbol, transicao.ConsumingStack[0], string.Join(",", transicao.PushStack.ToArray().Select(c => c.Name).ToArray())); } GViewer viewer = new GViewer(); viewer.NavigationVisible = false; viewer.OutsideAreaBrush = Brushes.White; //viewer.RemoveToolbar(); viewer.Graph = grafoAutomato; viewer.Dock = System.Windows.Forms.DockStyle.Fill; pnlAutomato.Controls.Clear(); pnlAutomato.Controls.Add(viewer); }
private void SimulationInitialize(bool moveFirsStep) { //clear the trace and visited table Traces.Clear(); visited.Clear(); ListView_Trace.Items.Clear(); //get the starting process //create the initial step EventStepSim initialStep = new EventStepSim(Spec.SimulationInitialization(this.ComboBox_Process.Text)); //new EventStepSim(startingProcess, Common.Ultility.Constants.INITIAL_EVENT, null, SpecProcess.GetEnvironment())); //use the process string as the definition ref string, this is the only special case needs to be taken care of //initialStep.ProcessToString = startingProcess.Def.ToString(); //todo: tobe checked //initialStep.ProcessToString = startingProcess.ToString(); InitialState = initialStep.StepID; //string initialLabel = initialStep.ToFullString(); AddToTrace("0", initialStep, "1", InitialState); CurrentEnableEventList.Clear(); if (moveFirsStep) { //try //{ List<EventStepSim> list = initialStep.MakeOneMove(HideTauTransition); for (int i = 0; i < list.Count; i++) { EventStepSim step = list[i]; step.SourceProcess = InitialState; step.IsUnvisitedStep = true; list[i] = step; } CurrentEnableEventList.AddRange(list); //} //catch (Exception ex) //{ //} } visited.Add(InitialState, null); g = new Graph("Graph"); //g.GraphAttr.Orientation = System.Windows.Forms.Orientation.Landscape; g.Attr.LayerDirection = Direction; Node n = g.AddNode(InitialState); n.Attr.FillColor = Color.Red; n.LabelText = "1"; n.UserData = initialStep; //initialLabel; Node tempN = g.AddNode(INITIAL_STATE); tempN.Attr.LineWidth = 0; tempN.Attr.Color = Color.White; tempN.LabelText = ""; tempN.UserData = ""; g.AddEdge(INITIAL_STATE, InitialState); //clear the mapping table Mapping.Clear(); Mapping.Add(GetTraceEvent(this.ListView_Trace.Items.Count) + InitialState, new ProcessData(initialStep, CloneGraph(g), CloneEnabledEvent())); SimulatorViewer.Graph = g; SimulatorViewer.Validate(); FillCurrentEnabledList(); UpdateStore(initialStep); WarningFlag = false; }
static void BindNodes(Graph graph, GeometryGraph geomGraph, Dictionary<GeomNode, string> nodeIds) { foreach (var node in geomGraph.Nodes) { if (IsUnderCollapsedCluster(node)) continue; string id = nodeIds.Count.ToString(); var n = graph.AddNode(id); n.GeometryNode = node; n.Attr.Color = new Color(50, 100, 100, 0); n.Attr.Shape = Shape.DrawFromGeometry; n.Label.Width = node.Width; n.Label.Owner = n; n.Label.Height = node.Height; n.LabelText = node.DebugId != null ? node.DebugId.ToString().Substring(0, Math.Min(5, node.DebugId.ToString().Length)) : node.UserData == null ? id : node.UserData.ToString().Substring(0, Math.Min(5, node.UserData.ToString().Length)); nodeIds[node] = id; } }
// Returns the last used id private int PopulateGraph(Graph graph, SyntaxWrapper wrapper, int id, string parentId) { // Check if filtering if ((wrapper.GetSyntaxObject() is SyntaxToken && _syntaxTokenCheckBox != null && !_syntaxTokenCheckBox.Checked) || (wrapper.GetSyntaxObject() is SyntaxTrivia && _syntaxTriviaCheckBox != null && !_syntaxTriviaCheckBox.Checked)) { return id; } // Create the node string nodeId = id.ToString(); Node node = new Node(nodeId); Color color = wrapper.GetColor(); node.Attr.FillColor = new Microsoft.Msagl.Drawing.Color(color.R, color.G, color.B); node.Attr.LabelMargin = 10; node.LabelText = wrapper.GetGraphText(); node.Label.FontColor = Microsoft.Msagl.Drawing.Color.White; node.Label.FontStyle = (Microsoft.Msagl.Drawing.FontStyle)(int) wrapper.GetGraphFontStyle(); graph.AddNode(node); // Add the edge if (parentId != null) { graph.AddEdge(parentId, nodeId); } // Descend IEnumerable children = wrapper.GetChildren(); if (children != null) { // Note that we have to iterate children in reverse order to get them to layout in the correct order foreach (SyntaxWrapper childWrapper in children.Cast<SyntaxWrapper>().Reverse()) { id = PopulateGraph(graph, childWrapper, id + 1, nodeId); } } return id; }
public void ShowDetailedMatch(object[] data) { if (data == null) { StatusLabel_Status.Text = "No Match Data"; SimulatorViewer.Graph = new Graph(); SimulatorViewer.Validate(); return; } Graph graph = new Graph(); List <PairUpCandidate> matches = data[1] as List <PairUpCandidate>; foreach (PairUpCandidate nodePair in matches) { if (nodePair.enclosingPairupElement is GraphNode) { AbstractGraphElement left = nodePair.left as AbstractGraphElement; AbstractGraphElement right = nodePair.right as AbstractGraphElement; if (!nodePair.isPairUpWithEpsilon()) // matched nodes { graph.AddNode(left.additionalInfo + "/" + right.additionalInfo); } else // unmatched nodes { if (!(nodePair.left is EpsilonGraphElement)) { Node node = graph.AddNode("l" + left.additionalInfo.ToString()); node.Attr.Color = DifferenceDisplayForm.LeftUnmatchColor; } if (!(nodePair.right is EpsilonGraphElement)) { Node node = graph.AddNode("r" + right.additionalInfo.ToString()); node.Attr.Color = DifferenceDisplayForm.RightUnmatchColor; } } } } foreach (PairUpCandidate edgePair in matches) { string srcNodePairLabel = ""; string trgNodePairLabel = ""; if (edgePair.enclosingPairupElement is GraphEdge) { PairUpGraphNode sourceNodePair = (edgePair.enclosingPairupElement as GraphEdge).Source() as PairUpGraphNode; PairUpGraphNode targetNodePair = (edgePair.enclosingPairupElement as GraphEdge).Target() as PairUpGraphNode; PairUpCandidate srcPairUpCandidate = sourceNodePair.candidate; PairUpCandidate trgPairUpCandidate = targetNodePair.candidate; AbstractGraphElement leftNode = srcPairUpCandidate.left as AbstractGraphElement; AbstractGraphElement rightNode = srcPairUpCandidate.right as AbstractGraphElement; if (!srcPairUpCandidate.isPairUpWithEpsilon()) // matched nodes { Debug.Assert(leftNode != null && rightNode != null); srcNodePairLabel = leftNode.additionalInfo + "/" + rightNode.additionalInfo; } else // unmatched nodes { if (!(srcPairUpCandidate.left is EpsilonGraphElement)) { Debug.Assert(leftNode != null); srcNodePairLabel = "l" + leftNode.additionalInfo.ToString(); } if (!(srcPairUpCandidate.right is EpsilonGraphElement)) { Debug.Assert(rightNode != null); srcNodePairLabel = "r" + rightNode.additionalInfo.ToString(); } } leftNode = trgPairUpCandidate.left as AbstractGraphElement; rightNode = trgPairUpCandidate.right as AbstractGraphElement; if (!trgPairUpCandidate.isPairUpWithEpsilon()) // matched nodes { Debug.Assert(leftNode != null && rightNode != null); trgNodePairLabel = leftNode.additionalInfo + "/" + rightNode.additionalInfo; } else // unmatched nodes { if (!(trgPairUpCandidate.left is EpsilonGraphElement)) { Debug.Assert(leftNode != null); trgNodePairLabel = "l" + leftNode.additionalInfo.ToString(); } if (!(trgPairUpCandidate.right is EpsilonGraphElement)) { Debug.Assert(rightNode != null); trgNodePairLabel = "r" + rightNode.additionalInfo.ToString(); } } /*srcNodePairLabel = ((srcPairUpCandidate.left is AbstractGraphElement) ? (srcPairUpCandidate.left as AbstractGraphElement).additionalInfo : "") + "/" + * ((srcPairUpCandidate.right is AbstractGraphElement) ? (srcPairUpCandidate.right as AbstractGraphElement).additionalInfo : ""); * srcNodePairLabel = srcNodePairLabel.Trim('/'); * * trgNodePairLabel = ((trgPairUpCandidate.left is AbstractGraphElement) ? (trgPairUpCandidate.left as AbstractGraphElement).additionalInfo : "") + "/" + * ((trgPairUpCandidate.right is AbstractGraphElement) ? (trgPairUpCandidate.right as AbstractGraphElement).additionalInfo : ""); * * trgNodePairLabel = trgNodePairLabel.Trim('/');*/ if (!edgePair.isPairUpWithEpsilon()) // matched edges, src/trg must be matched node pairs { if (edgePair.left.getLabel() == "" && edgePair.right.getLabel() == "") { graph.AddEdge(srcNodePairLabel, trgNodePairLabel); } else { graph.AddEdge(srcNodePairLabel, edgePair.left.getLabel() + "/" + edgePair.right.getLabel(), trgNodePairLabel); } } else // unmatched nodes { if (!(edgePair.left is EpsilonGraphElement)) { Edge edge = graph.AddEdge(srcNodePairLabel, edgePair.left.getLabel(), trgNodePairLabel); edge.Attr.Color = DifferenceDisplayForm.LeftUnmatchColor; } else { Edge edge = graph.AddEdge(srcNodePairLabel, edgePair.right.getLabel(), trgNodePairLabel); edge.Attr.Color = DifferenceDisplayForm.RightUnmatchColor; } } } } this.SimulatorViewer.Graph = graph; this.SimulatorViewer.Invalidate(false); StatusLabel_Status.Text = "Graph Generated: " + (SimulatorViewer.Graph.NodeCount - 1) + " Nodes, " + (SimulatorViewer.Graph.EdgeCount - 1) + " Edges"; }
private Graph RenderGraph(LangFile langFile) { var graph = new Graph("OpenFoodFacts Category Taxonomy"); var languageComparer = new LanguageByImportanceComparer(langFile.TranslationSets); var parentsComparer = new ParentsComparer(new AlphabeticalTranslationSetComparer(languageComparer, EvaluateMostImportantTranslation, GetLabel)); foreach (var translationSet in langFile.TranslationSets.OrderBy(ts => ts.Parents, parentsComparer)) { if (!translationSet.Translations.Any()) { continue; } var translation = EvaluateMostImportantTranslation(translationSet, languageComparer); var translationLabel = GetLabel(translation); if (translationSet.Parents.Any()) { foreach (var parent in translationSet.Parents) { var parentTranslation = EvaluateMostImportantTranslation(parent, languageComparer); var parentTranslationLabel = GetLabel(parentTranslation); graph.AddEdge(parentTranslationLabel, translationLabel); } } else { graph.AddNode(translationLabel); } } return graph; }
static void BindClusters(Graph graph, GeometryGraph geomGraph, Dictionary<GeomNode, string> nodeIds) { foreach (var cluster in geomGraph.RootCluster.AllClustersWidthFirstExcludingSelfAvoidingChildrenOfCollapsed()) { string id = nodeIds.Count.ToString(); var n = graph.AddNode(id); n.GeometryNode = cluster; n.Attr.Color = Color.RosyBrown; if (cluster.BoundaryCurve != null) { n.Label.Width = cluster.Width/2; n.Label.Owner = n; n.Label.Height = cluster.Height/2; n.Label.Owner = n; n.LabelText = cluster.DebugId != null ? cluster.DebugId.ToString().Substring(0, Math.Min(5, cluster.DebugId.ToString().Length)) : cluster.UserData == null ? "" : cluster.UserData.ToString().Substring(0, Math.Min(5, cluster.UserData.ToString().Length)); } nodeIds[cluster] = id; } }
public static void DrawArrow(GViewer gLocalViewer, GraphItem nodeId1, GraphItem nodeId2, bool isSelected, Microsoft.Msagl.Drawing.Graph graph, IGraphPath path) { ReportQueryItemPathResult prevItem = null; int index = 1; bool isSelectedEdgeDrawn = false; foreach (ReportQueryItemPathResult item in nodeId1.QueryItem.Paths) { Node sourceNode = graph.FindNode(item.UniqueID); if (sourceNode == null) { sourceNode = new Node(item.UniqueID); if (item.Name.Length > 12) { sourceNode.Label.Text = string.Format("{0}...", item.Name.Substring(0, 6)); } else { sourceNode.Label.Text = item.Name; } graph.AddNode(sourceNode); } GraphItem newItem = new GraphItem(); newItem.Column = nodeId1.Column; newItem.CurrentPathIndex = item.NodeId; newItem.FileName = nodeId1.FileName; newItem.GraphX = nodeId1.GraphX; newItem.GraphY = nodeId1.GraphY; newItem.IsMultiReletions = nodeId1.IsMultiReletions; newItem.IsPrimary = nodeId1.IsPrimary; newItem.IsSelected = nodeId1.IsSelected; newItem.Length = nodeId1.Length; newItem.Line = nodeId1.Line; newItem.Name = nodeId1.Name; newItem.Parent = nodeId1.Parent; newItem.QueryItem = nodeId1.QueryItem; newItem.RelatedTo = nodeId1.RelatedTo; newItem.RelationsFrom = nodeId1.RelationsFrom; sourceNode.UserData = newItem; if (isSelected && item.UniqueID == DrawingHelper.SelectedPathItemUniqueID && !isEdgeSelected) { newItem.IsSelected = true; SetDrawDelegateByNode(sourceNode, NodeTypes.NormalSelected); } else { newItem.IsSelected = false; SetDrawDelegateByNode(sourceNode, NodeTypes.Normal); } if (prevItem != null) { Edge edge = IsEdgeExisted(sourceNode, prevItem.UniqueID); if (edge == null) { edge = graph.AddEdge(prevItem.UniqueID, item.UniqueID); edge.Attr.ArrowheadAtTarget = ArrowStyle.Normal; edge.Attr.ArrowheadLength = 10; edge.Attr.LineWidth = 2; edge.Attr.Weight = 2; path.QueryItemResult = nodeId1.QueryItem; edge.UserData = path; } SetMaxReletions(edge); if (isSelected && ((SelectedNodeUniqueID == nodeId1.UniqueID && !isEdgeSelected) || (IsContainPath(nodeId1.QueryItem.Paths) && isEdgeSelected) || (DrawingHelper.SelectedNodeUniqueID == null) )) { edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Black; edge.Attr.Weight = 2; edge.Attr.LineWidth = 2; isSelectedEdgeDrawn = true; } else { edge.Attr.Color = Microsoft.Msagl.Drawing.Color.DarkGray; edge.Attr.Weight = 2; edge.Attr.LineWidth = 2; } } prevItem = item; index++; } prevItem = null; index = 1; foreach (ReportQueryItemPathResult item in nodeId2.QueryItem.Paths) { Node sourceNode = graph.FindNode(item.UniqueID); if (sourceNode == null) { sourceNode = new Node(item.UniqueID); if (item.Name.Length > 12) { sourceNode.Label.Text = string.Format("{0}...", item.Name.Substring(0, 6)); } else { sourceNode.Label.Text = item.Name; } graph.AddNode(sourceNode); } GraphItem newItem = new GraphItem(); newItem.Column = nodeId2.Column; newItem.CurrentPathIndex = item.NodeId; newItem.FileName = nodeId2.FileName; newItem.GraphX = nodeId2.GraphX; newItem.GraphY = nodeId2.GraphY; newItem.IsMultiReletions = nodeId2.IsMultiReletions; newItem.IsPrimary = nodeId2.IsPrimary; newItem.IsSelected = nodeId2.IsSelected; newItem.Length = nodeId2.Length; newItem.Line = nodeId2.Line; newItem.Name = nodeId2.Name; newItem.Parent = nodeId2.Parent; newItem.QueryItem = nodeId2.QueryItem; newItem.RelatedTo = nodeId2.RelatedTo; newItem.RelationsFrom = nodeId2.RelationsFrom; sourceNode.UserData = newItem; if (isSelected && item.UniqueID == DrawingHelper.SelectedPathItemUniqueID && !isEdgeSelected) { newItem.IsSelected = true; SetDrawDelegateByNode(sourceNode, NodeTypes.NormalSelected); } else { newItem.IsSelected = false; SetDrawDelegateByNode(sourceNode, NodeTypes.Normal); } if (prevItem != null) { Edge edge = IsEdgeExisted(sourceNode, prevItem.UniqueID); if (edge == null) { edge = graph.AddEdge(prevItem.UniqueID, item.UniqueID); edge.Attr.ArrowheadAtTarget = ArrowStyle.Normal; edge.Attr.ArrowheadLength = 10; path.QueryItemResult = nodeId2.QueryItem; edge.UserData = path; } SetMaxReletions(edge); if (isSelected && ((SelectedNodeUniqueID == nodeId2.UniqueID && !isEdgeSelected) || (IsContainPath(nodeId2.QueryItem.Paths) && isEdgeSelected) || (DrawingHelper.SelectedNodeUniqueID == null) )) { if (!isSelectedEdgeDrawn || isEdgeSelected) { edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Black; edge.Attr.Weight = 2; edge.Attr.LineWidth = 2; } } else { //if (!isSelectedEdgeDrawn || !isEdgeSelected) if (!isSelectedEdgeDrawn) { edge.Attr.Color = Microsoft.Msagl.Drawing.Color.DarkGray; edge.Attr.Weight = 2; edge.Attr.LineWidth = 2; } } } prevItem = item; index++; } bool isTopNodeFound = false; if (isSelected && ((IsContainPath(nodeId1.QueryItem.Paths) && isEdgeSelected) || (DrawingHelper.SelectedNodeUniqueID == null)) ) { Node firstNode = graph.FindNode(nodeId1.QueryItem.Paths[0].UniqueID); IGraphItem item = firstNode.UserData as IGraphItem; item.IsSelected = true; SetDrawDelegateByNode(firstNode, NodeTypes.NormalSelected); isTopNodeFound = true; SelectedNodeUniqueID = nodeId1.UniqueID; } if (!isTopNodeFound && isSelected && ((IsContainPath(nodeId2.QueryItem.Paths) && isEdgeSelected) || (DrawingHelper.SelectedNodeUniqueID == null)) ) { Node firstNode = graph.FindNode(nodeId2.QueryItem.Paths[0].UniqueID); IGraphItem item = firstNode.UserData as IGraphItem; item.IsSelected = true; SetDrawDelegateByNode(firstNode, NodeTypes.NormalSelected); SelectedNodeUniqueID = nodeId2.UniqueID; } }
static Graph CreateGraphFromParsedStuff(Dictionary<string, Tuple<int, int, int, int>> labelsToGeom, List<Tuple<string, string>> edges) { var graph = new Graph(); foreach (var label in labelsToGeom.Keys) graph.AddNode(label); foreach (var tuple in edges) { var e=graph.AddEdge(tuple.Item1, tuple.Item2); e.Attr.ArrowheadAtTarget = ArrowStyle.None; } graph.CreateGeometryGraph(); foreach (var node in graph.Nodes) { var tuple = labelsToGeom[node.Id]; int centerX = tuple.Item1; int centerY = tuple.Item2; int w=tuple.Item3; int h = tuple.Item4; node.GeometryNode.BoundaryCurve = new RoundedRect( new Rectangle(centerX-(double)w/2, centerY-(double)h/2, new Microsoft.Msagl.Core.Geometry.Point(tuple.Item3, tuple.Item4)), 3, 3); } var router = new SplineRouter(graph.GeometryGraph, 1, 1, Math.PI / 6, null); router.Run(); graph.GeometryGraph.UpdateBoundingBox(); //LayoutAlgorithmSettings.ShowGraph(graph.GeometryGraph); return graph; }
private void Draw(Graph<Symbol, double> g) { treeViewSyn.Nodes.Clear(); if (g != null && g.Root != null) { Graph graph = new Graph("Graph"); //graph.Attr.LayerDirection = LayerDirection.TB; Node<Symbol, double> node = g.Root; TreeNode treeNode; Stack<Node<Symbol, double>> stack = new Stack<Node<Symbol, double>>(); Stack<TreeNode> stackTreeNode = new Stack<TreeNode>(); stackTreeNode.Push(null); stack.Push(node); while (stack.Count > 0) { node = stack.Pop(); treeNode = stackTreeNode.Pop(); var treeNodeNext = AddNode(node, treeNode); string str = "Root"; if (node.Info != null) str = node.Info.Name; var no = graph.AddNode(node.Name); no.Attr.Shape = Shape.Circle; no.LabelText = str; foreach (var transition in System.Linq.Enumerable.Reverse(node.Edges)) { Edge arco = graph.AddEdge(node.Name, "", transition.Destiny.Name); System.Drawing.Color c = Utils.GetColor(transition.Cost); var color = new Microsoft.Msagl.Drawing.Color((byte)c.R, (byte)c.G, (byte)c.B); arco.Attr.Color = color; arco.Attr.AddStyle(Style.Bold); arco.Attr.LineWidth = 5; arco.LabelText = transition.Cost.ToString("n2"); stack.Push(transition.Destiny); stackTreeNode.Push(treeNodeNext); } } GViewer viewer = new GViewer(); // viewer.CurrentLayoutMethod = LayoutMethod.Ranking; viewer.NavigationVisible = false; viewer.OutsideAreaBrush = Brushes.White; viewer.ToolBarIsVisible = false; viewer.Graph = graph; viewer.Dock = System.Windows.Forms.DockStyle.Fill; pnlGraph.Controls.Clear(); pnlGraph.Controls.Add(viewer); treeViewSyn.ExpandAll(); } }
Graph GetTypeGraph() { var g = new Graph("Types", "id"); var table = new Hashtable(); foreach (XmlSchemaType st in set.GlobalTypes.Values) { if (st != null) { if (st.QualifiedName == null || st.QualifiedName.Namespace != "http://www.w3.org/2001/XMLSchema") { table[st] = null; } } } foreach (XmlSchemaType ct in new ArrayList(table.Keys)) { XmlSchemaType baseType = ct.BaseXmlSchemaType; if (baseType != null && baseType.QualifiedName.Namespace != "http://www.w3.org/2001/XMLSchema") { var b1 = table[ct] as Node; if (b1 == null) { b1 = g.AddNode(GetId(ct)); b1.LabelText = GetLabel(ct); b1.Attr.Shape = Shape.Box; b1.Attr.XRadius = b1.Attr.YRadius = 2; // rounded box. b1.Attr.LabelMargin = 5; SetNodeColors(b1); table[ct] = b1; } Node b2 = g.AddNode(GetId(baseType)); b2.LabelText = GetLabel(baseType); b2.Attr.Shape = Shape.Box; b2.Attr.XRadius = b2.Attr.YRadius = 2; // rounded box. SetNodeColors(b2); b2.Attr.LabelMargin = 5; g.AddEdge(b1.Attr.Id, b2.Attr.Id); } } g.Attr.LayerDirection = direction; return g; }
public static void _DrawArrow(GViewer gLocalViewer, GraphItem nodeId1, GraphItem nodeId2, bool isSelected, Microsoft.Msagl.Drawing.Graph graph, IGraphPath path) { #region Set node 1 caption bool isNewEdge = false; //Microsoft.Msagl.Drawing.Graph graph = gLocalViewer.Graph; Node sourceNode = graph.FindNode(nodeId1.UniqueID); if (sourceNode == null) { isNewEdge = true; sourceNode = new Node(nodeId1.UniqueID); if (nodeId1.Name.Length > 12) { sourceNode.Label.Text = string.Format("{0}...", nodeId1.Name.Substring(0, 6)); } else { sourceNode.Label.Text = nodeId1.Name; } } #endregion #region Set node 2 caption Node targetNode = graph.FindNode(nodeId2.UniqueID); if (targetNode == null) { isNewEdge = true; targetNode = new Node(nodeId2.UniqueID); if (nodeId2.Name.Length > 12) { targetNode.Label.Text = string.Format("{0}...", nodeId2.Name.Substring(0, 6)); } else { targetNode.Label.Text = nodeId2.Name; } } #endregion #region Set Drawing type GraphItem nodeItem1 = sourceNode.UserData as GraphItem; GraphItem nodeItem2 = targetNode.UserData as GraphItem; sourceNode.UserData = nodeId1; targetNode.UserData = nodeId2; #endregion if (isNewEdge) { graph.AddNode(sourceNode); graph.AddNode(targetNode); if (nodeId1.UniqueID != nodeId2.UniqueID) { Edge edge = graph.AddEdge(nodeId1.UniqueID, nodeId2.UniqueID); edge.UserData = path; } } else { if (!IsNodesConnected(sourceNode, targetNode)) { if (nodeId1.UniqueID != nodeId2.UniqueID) { Edge edge = graph.AddEdge(nodeId1.UniqueID, nodeId2.UniqueID); edge.UserData = path; } } } SetNodeColor(graph, nodeId1, nodeId2, sourceNode, targetNode, isSelected); }
private Graph BuildGraphFrom(VisualGraphGeneratedMessage affectedGraph) { var graph = new Graph("graph") { Attr = {BackgroundColor = Color.Transparent} }; if (affectedGraph.Connections != null) { _gViewer.LayoutAlgorithmSettingsButtonVisible = true; _gViewer.ForeColor = System.Drawing.Color.FromArgb(1,2,3); foreach (var x in affectedGraph.Connections) { var edge = graph.AddEdge(x.From, x.To); if (_mode == DisplayMode.Dark) { edge.Attr.Color = Color.White; } } } graph.Attr.LayerDirection = LayerDirection.LR; if (affectedGraph.Nodes != null) foreach (var y in affectedGraph.Nodes) { var n = graph.FindNode(y.FullName) ?? graph.AddNode(y.FullName); n.LabelText = y.DisplayName; n.Attr.Shape = Shape.Box; if (y.IsRootNode) n.Attr.FillColor = Color.LightGreen; else if (y.IsChange) n.Attr.FillColor = Color.Maroon; else if (y.IsTest && y.IsProfiledTest) n.Attr.FillColor = Color.Yellow; else if (y.IsTest) n.Attr.FillColor = Color.DarkGoldenrod; else if (y.IsInterface) n.Attr.FillColor = Color.LightBlue; //TODO GREG PUT ON FEATURE TOGGLE else if (false && y.Complexity > 15) n.Attr.FillColor = Color.LightPink; else n.Attr.FillColor = Color.White; } return graph; }