Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.cs @ 10471

Last change on this file since 10471 was 10471, checked in by bburlacu, 10 years ago

#2076: Thanks for the feedback:

  • I removed the ILayoutNode Interfaces
  • Fixed the error that was causing it to crash in the textual representation
  • The ancestor is a node on the path between the root and the current node (from the paper), but in the algorithm it's assigned differently
  • Parent is the immediate parent

I also increased the node label text size a bit and did some cosmetic improvements.

File size: 16.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Drawing.Imaging;
26using System.IO;
27using System.Linq;
28using System.Windows.Forms;
29using Point = System.Drawing.Point;
30
31namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
32  public partial class SymbolicExpressionTreeChart : UserControl {
33    private Image image;
34    private readonly StringFormat stringFormat;
35    private Dictionary<ISymbolicExpressionTreeNode, VisualSymbolicExpressionTreeNode> visualTreeNodes;
36    private Dictionary<Tuple<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>, VisualSymbolicExpressionTreeNodeConnection> visualLines;
37    private readonly ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode> layoutEngine;
38    private readonly SymbolicExpressionTreeLayoutAdapter layoutAdapter;
39
40    private const int preferredNodeWidth = 70;
41    private const int preferredNodeHeight = 46;
42    private const int minHorizontalDistance = 20;
43    private const int minVerticalDistance = 20;
44
45
46    public SymbolicExpressionTreeChart() {
47      InitializeComponent();
48      this.image = new Bitmap(Width, Height);
49      this.stringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
50      this.spacing = 5;
51      this.lineColor = Color.Black;
52      this.backgroundColor = Color.White;
53      this.textFont = new Font(FontFamily.GenericSansSerif, 12);
54      layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>();
55      layoutAdapter = new SymbolicExpressionTreeLayoutAdapter();
56    }
57
58    public SymbolicExpressionTreeChart(ISymbolicExpressionTree tree)
59      : this() {
60      layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>();
61      layoutAdapter = new SymbolicExpressionTreeLayoutAdapter();
62      this.Tree = tree;
63    }
64
65    #region Public properties
66    private int spacing;
67    public int Spacing {
68      get { return this.spacing; }
69      set {
70        this.spacing = value;
71        this.Repaint();
72      }
73    }
74
75    private Color lineColor;
76    public Color LineColor {
77      get { return this.lineColor; }
78      set {
79        this.lineColor = value;
80        this.Repaint();
81      }
82    }
83
84    private Color backgroundColor;
85    public Color BackgroundColor {
86      get { return this.backgroundColor; }
87      set {
88        this.backgroundColor = value;
89        this.Repaint();
90      }
91    }
92
93    private Font textFont;
94    public Font TextFont {
95      get { return this.textFont; }
96      set {
97        this.textFont = value;
98        this.Repaint();
99      }
100    }
101
102    private ISymbolicExpressionTree tree;
103    public ISymbolicExpressionTree Tree {
104      get { return this.tree; }
105      set {
106        tree = value;
107        visualTreeNodes = new Dictionary<ISymbolicExpressionTreeNode, VisualSymbolicExpressionTreeNode>();
108        visualLines = new Dictionary<Tuple<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>, VisualSymbolicExpressionTreeNodeConnection>();
109        if (tree != null) {
110          foreach (ISymbolicExpressionTreeNode node in tree.IterateNodesPrefix()) {
111            visualTreeNodes[node] = new VisualSymbolicExpressionTreeNode(node);
112            if (node.Parent != null) visualLines[Tuple.Create(node.Parent, node)] = new VisualSymbolicExpressionTreeNodeConnection();
113          }
114        }
115        Repaint();
116      }
117    }
118
119    private bool suspendRepaint;
120    public bool SuspendRepaint {
121      get { return suspendRepaint; }
122      set { suspendRepaint = value; }
123    }
124    #endregion
125
126    protected override void OnPaint(PaintEventArgs e) {
127      e.Graphics.DrawImage(image, 0, 0);
128      base.OnPaint(e);
129    }
130    protected override void OnResize(EventArgs e) {
131      base.OnResize(e);
132      if (this.Width <= 1 || this.Height <= 1)
133        this.image = new Bitmap(1, 1);
134      else
135        this.image = new Bitmap(Width, Height);
136      this.Repaint();
137    }
138
139    public void Repaint() {
140      if (!suspendRepaint) {
141        this.GenerateImage();
142        this.Refresh();
143      }
144    }
145
146    public void RepaintNodes() {
147      if (!suspendRepaint) {
148        using (var graphics = Graphics.FromImage(image)) {
149          graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
150          graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
151          foreach (var visualNode in visualTreeNodes.Values) {
152            DrawTreeNode(graphics, visualNode);
153          }
154        }
155        this.Refresh();
156      }
157    }
158
159    public void RepaintNode(VisualSymbolicExpressionTreeNode visualNode) {
160      if (!suspendRepaint) {
161        using (var graphics = Graphics.FromImage(image)) {
162          graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
163          graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
164          DrawTreeNode(graphics, visualNode);
165        }
166        this.Refresh();
167      }
168    }
169
170    private void GenerateImage() {
171      using (Graphics graphics = Graphics.FromImage(image)) {
172        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
173        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
174        graphics.Clear(backgroundColor);
175        if (tree != null) {
176          DrawFunctionTree(tree, graphics, preferredNodeWidth, preferredNodeHeight, minHorizontalDistance, minVerticalDistance);
177        }
178      }
179    }
180
181    public VisualSymbolicExpressionTreeNode GetVisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode) {
182      if (visualTreeNodes.ContainsKey(symbolicExpressionTreeNode))
183        return visualTreeNodes[symbolicExpressionTreeNode];
184      return null;
185    }
186
187    public VisualSymbolicExpressionTreeNodeConnection GetVisualSymbolicExpressionTreeNodeConnection(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {
188      if (child.Parent != parent) throw new ArgumentException();
189      var key = Tuple.Create(parent, child);
190      VisualSymbolicExpressionTreeNodeConnection connection = null;
191      visualLines.TryGetValue(key, out connection);
192      return connection;
193    }
194
195    #region events
196    public event MouseEventHandler SymbolicExpressionTreeNodeClicked;
197    protected virtual void OnSymbolicExpressionTreeNodeClicked(object sender, MouseEventArgs e) {
198      var clicked = SymbolicExpressionTreeNodeClicked;
199      if (clicked != null)
200        clicked(sender, e);
201    }
202
203    protected virtual void SymbolicExpressionTreeChart_MouseClick(object sender, MouseEventArgs e) {
204      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
205      if (visualTreeNode != null) {
206        OnSymbolicExpressionTreeNodeClicked(visualTreeNode, e);
207      }
208    }
209
210    public event MouseEventHandler SymbolicExpressionTreeNodeDoubleClicked;
211    protected virtual void OnSymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
212      var doubleClicked = SymbolicExpressionTreeNodeDoubleClicked;
213      if (doubleClicked != null)
214        doubleClicked(sender, e);
215    }
216
217    protected virtual void SymbolicExpressionTreeChart_MouseDoubleClick(object sender, MouseEventArgs e) {
218      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
219      if (visualTreeNode != null)
220        OnSymbolicExpressionTreeNodeDoubleClicked(visualTreeNode, e);
221    }
222
223    public event ItemDragEventHandler SymbolicExpressionTreeNodeDrag;
224    protected virtual void OnSymbolicExpressionTreeNodeDragDrag(object sender, ItemDragEventArgs e) {
225      var dragged = SymbolicExpressionTreeNodeDrag;
226      if (dragged != null)
227        dragged(sender, e);
228    }
229
230    private VisualSymbolicExpressionTreeNode draggedSymbolicExpressionTree;
231    private MouseButtons dragButtons;
232    private void SymbolicExpressionTreeChart_MouseDown(object sender, MouseEventArgs e) {
233      this.dragButtons = e.Button;
234      this.draggedSymbolicExpressionTree = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
235    }
236    private void SymbolicExpressionTreeChart_MouseUp(object sender, MouseEventArgs e) {
237      this.draggedSymbolicExpressionTree = null;
238      this.dragButtons = MouseButtons.None;
239    }
240
241    private void SymbolicExpressionTreeChart_MouseMove(object sender, MouseEventArgs e) {
242      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
243      if (draggedSymbolicExpressionTree != null &&
244        draggedSymbolicExpressionTree != visualTreeNode) {
245        OnSymbolicExpressionTreeNodeDragDrag(draggedSymbolicExpressionTree, new ItemDragEventArgs(dragButtons, draggedSymbolicExpressionTree));
246        draggedSymbolicExpressionTree = null;
247      } else if (draggedSymbolicExpressionTree == null &&
248        visualTreeNode != null) {
249        string tooltipText = visualTreeNode.ToolTip;
250        if (this.toolTip.GetToolTip(this) != tooltipText)
251          this.toolTip.SetToolTip(this, tooltipText);
252
253      } else if (visualTreeNode == null)
254        this.toolTip.SetToolTip(this, "");
255    }
256
257    public VisualSymbolicExpressionTreeNode FindVisualSymbolicExpressionTreeNodeAt(int x, int y) {
258      foreach (var visualTreeNode in visualTreeNodes.Values) {
259        if (x >= visualTreeNode.X && x <= visualTreeNode.X + visualTreeNode.Width &&
260            y >= visualTreeNode.Y && y <= visualTreeNode.Y + visualTreeNode.Height)
261          return visualTreeNode;
262      }
263      return null;
264    }
265    #endregion
266
267    #region methods for painting the symbolic expression tree
268
269    private void DrawFunctionTree(ISymbolicExpressionTree tree, Graphics graphics, int preferredWidth, int preferredHeight, int minHDistance, int minVDistance) {
270      var layoutNodes = layoutAdapter.Convert(tree).ToList();
271      layoutEngine.Reset();
272      layoutEngine.Root = layoutNodes[0];
273      layoutEngine.AddNodes(layoutNodes);
274      layoutEngine.MinHorizontalSpacing = (preferredNodeWidth + minHDistance);
275      layoutEngine.MinVerticalSpacing = (preferredNodeHeight + minVDistance);
276      layoutEngine.CalculateLayout();
277      var bounds = layoutEngine.Bounds();
278      double sx = this.Width / (bounds.Width + preferredWidth);
279      if (sx > 1) sx = 1;
280      double sy = this.Height / (bounds.Height + preferredHeight);
281      if (sy > 1) sy = 1;
282      double dx = (this.Width - bounds.Width + preferredWidth) / 2;
283      if (dx < 0) dx = 0;
284      double dy = (this.Height - bounds.Height + preferredHeight) / 2;
285      if (dy < 0) dy = 0;
286
287      var levels = layoutNodes.GroupBy(n => n.Level, n => n);
288
289      foreach (var level in levels) {
290        var nodes = level.ToList();
291        double min = 0;
292        for (int i = 0; i < nodes.Count - 1; ++i) {
293          var w = (nodes[i + 1].X - nodes[i].X) * sx - preferredWidth;
294          if (w < min) min = w;
295        }
296        if (min > 0) min = 0;
297
298        foreach (var layoutNode in level) {
299          var visualNode = visualTreeNodes[layoutNode.Content];
300          visualNode.Width = (int)Math.Round(preferredWidth + min) - 2; // -2 to allow enough padding (1px on each side) for the node contour to be drawn
301          visualNode.Height = (int)Math.Round(preferredHeight * sy);
302          visualNode.X = (int)(Math.Round(layoutNode.X * sx + dx));
303          visualNode.Y = (int)(Math.Round(layoutNode.Y * sy + dy));
304          DrawTreeNode(graphics, visualNode);
305        }
306      }
307
308      graphics.ResetClip(); // reset clip region
309      // draw node connections
310      foreach (var visualNode in visualTreeNodes.Values) {
311        var node = visualNode.SymbolicExpressionTreeNode;
312        foreach (var subtree in node.Subtrees) {
313          var visualLine = GetVisualSymbolicExpressionTreeNodeConnection(node, subtree);
314          var visualSubtree = visualTreeNodes[subtree];
315          var origin = new Point(visualNode.X + visualNode.Width / 2, visualNode.Y + visualNode.Height);
316          var target = new Point(visualSubtree.X + visualSubtree.Width / 2, visualSubtree.Y);
317          using (var linePen = new Pen(visualLine.LineColor)) {
318            linePen.DashStyle = visualLine.DashStyle;
319            graphics.DrawLine(linePen, origin, target);
320          }
321        }
322      }
323    }
324
325    protected void DrawTreeNode(VisualSymbolicExpressionTreeNode visualTreeNode) {
326      using (var graphics = Graphics.FromImage(image)) {
327        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
328        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
329        DrawTreeNode(graphics, visualTreeNode);
330      }
331    }
332
333    protected void DrawTreeNode(Graphics graphics, VisualSymbolicExpressionTreeNode visualTreeNode) {
334      graphics.Clip = new Region(new Rectangle(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width + 1, visualTreeNode.Height + 1));
335      graphics.Clear(backgroundColor);
336      var node = visualTreeNode.SymbolicExpressionTreeNode;
337      using (var textBrush = new SolidBrush(visualTreeNode.TextColor))
338      using (var nodeLinePen = new Pen(visualTreeNode.LineColor))
339      using (var nodeFillBrush = new SolidBrush(visualTreeNode.FillColor)) {
340        //draw terminal node
341        if (node.SubtreeCount == 0) {
342          graphics.FillRectangle(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
343          graphics.DrawRectangle(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
344        } else {
345          graphics.FillEllipse(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
346          graphics.DrawEllipse(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
347        }
348        //draw name of symbol
349        var text = node.ToString();
350        graphics.DrawString(text, textFont, textBrush, new RectangleF(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height), stringFormat);
351      }
352    }
353    #endregion
354    #region save image
355    private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) {
356      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
357        string filename = saveFileDialog.FileName.ToLower();
358        if (filename.EndsWith("bmp")) SaveImageAsBitmap(filename);
359        else if (filename.EndsWith("emf")) SaveImageAsEmf(filename);
360        else SaveImageAsBitmap(filename);
361      }
362    }
363
364    public void SaveImageAsBitmap(string filename) {
365      if (tree == null) return;
366      Image image = new Bitmap(Width, Height);
367      using (Graphics g = Graphics.FromImage(image)) {
368        int height = this.Height / tree.Depth;
369        DrawFunctionTree(tree, g, 0, 0, Width, height);
370      }
371      image.Save(filename);
372    }
373
374    public void SaveImageAsEmf(string filename) {
375      if (tree == null) return;
376      using (Graphics g = CreateGraphics()) {
377        using (Metafile file = new Metafile(filename, g.GetHdc())) {
378          using (Graphics emfFile = Graphics.FromImage(file)) {
379            int height = this.Height / tree.Depth;
380            DrawFunctionTree(tree, emfFile, 0, 0, Width, height);
381          }
382        }
383        g.ReleaseHdc();
384      }
385    }
386    #endregion
387    #region export pgf/tikz
388    private void exportLatexToolStripMenuItem_Click(object sender, EventArgs e) {
389      using (var dialog = new SaveFileDialog { Filter = "Tex (*.tex)|*.tex" }) {
390        if (dialog.ShowDialog() != DialogResult.OK) return;
391        string filename = dialog.FileName.ToLower();
392        var formatter = new SymbolicExpressionTreeLatexFormatter();
393        File.WriteAllText(filename, formatter.Format(Tree));
394      }
395    }
396    #endregion
397  }
398}
Note: See TracBrowser for help on using the repository browser.