Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.cs @ 10138

Last change on this file since 10138 was 9996, checked in by bburlacu, 11 years ago

#1772: Removed unnecessary subproject (not included in solution). Merged changes from tree layout branch.

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 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("Times New Roman", 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      foreach (var ln in layoutNodes)
274        layoutEngine.AddNode(ln.Content, ln);
275      layoutEngine.MinHorizontalSpacing = (preferredNodeWidth + minHDistance);
276      layoutEngine.MinVerticalSpacing = (preferredNodeHeight + minVDistance);
277      layoutEngine.CalculateLayout();
278      var bounds = layoutEngine.Bounds();
279      double sx = this.Width / (bounds.Width + preferredWidth);
280      if (sx > 1) sx = 1;
281      double sy = this.Height / bounds.Height;
282      if (sy > 1) sy = 1;
283      double dx = (this.Width - bounds.Width) / 2;
284      if (dx < 0) dx = 0;
285      double dy = (this.Height - bounds.Height) / 2;
286      if (dy < 0) dy = 0;
287
288      var levels = layoutNodes.GroupBy(n => n.Level, n => n);
289
290      foreach (var level in levels) {
291        var nodes = level.ToList();
292        double min = 0;
293        for (int i = 0; i < nodes.Count - 1; ++i) {
294          var w = (nodes[i + 1].X - nodes[i].X) * sx - preferredWidth;
295          if (w < min) min = w;
296        }
297        if (min > 0) min = 0;
298
299        foreach (var layoutNode in level) {
300          var visualNode = visualTreeNodes[layoutNode.Content];
301          visualNode.Width = (int)Math.Round(preferredWidth + min) - 2; // -2 to allow enough padding (1px on each side) for the node contour to be drawn
302          visualNode.Height = (int)Math.Round(preferredHeight * sy);
303          visualNode.X = (int)(Math.Round(layoutNode.X * sx + dx));
304          visualNode.Y = (int)(Math.Round(layoutNode.Y * sy + dy));
305          DrawTreeNode(graphics, visualNode);
306        }
307      }
308
309      graphics.ResetClip(); // reset clip region
310      // draw node connections
311      foreach (var visualNode in visualTreeNodes.Values) {
312        var node = visualNode.SymbolicExpressionTreeNode;
313        foreach (var subtree in node.Subtrees) {
314          var visualLine = GetVisualSymbolicExpressionTreeNodeConnection(node, subtree);
315          var visualSubtree = visualTreeNodes[subtree];
316          var origin = new Point(visualNode.X + visualNode.Width / 2, visualNode.Y + visualNode.Height);
317          var target = new Point(visualSubtree.X + visualSubtree.Width / 2, visualSubtree.Y);
318          using (var linePen = new Pen(visualLine.LineColor)) {
319            linePen.DashStyle = visualLine.DashStyle;
320            graphics.DrawLine(linePen, origin, target);
321          }
322        }
323      }
324    }
325
326    protected void DrawTreeNode(VisualSymbolicExpressionTreeNode visualTreeNode) {
327      using (var graphics = Graphics.FromImage(image)) {
328        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
329        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
330        DrawTreeNode(graphics, visualTreeNode);
331      }
332    }
333
334    protected void DrawTreeNode(Graphics graphics, VisualSymbolicExpressionTreeNode visualTreeNode) {
335      graphics.Clip = new Region(new Rectangle(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width + 1, visualTreeNode.Height + 1));
336      graphics.Clear(backgroundColor);
337      var node = visualTreeNode.SymbolicExpressionTreeNode;
338      using (var textBrush = new SolidBrush(visualTreeNode.TextColor))
339      using (var nodeLinePen = new Pen(visualTreeNode.LineColor))
340      using (var nodeFillBrush = new SolidBrush(visualTreeNode.FillColor)) {
341        //draw terminal node
342        if (node.SubtreeCount == 0) {
343          graphics.FillRectangle(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
344          graphics.DrawRectangle(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
345        } else {
346          graphics.FillEllipse(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
347          graphics.DrawEllipse(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
348        }
349        //draw name of symbol
350        var text = node.ToString();
351        graphics.DrawString(text, textFont, textBrush, new RectangleF(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height), stringFormat);
352      }
353    }
354    #endregion
355    #region save image
356    private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) {
357      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
358        string filename = saveFileDialog.FileName.ToLower();
359        if (filename.EndsWith("bmp")) SaveImageAsBitmap(filename);
360        else if (filename.EndsWith("emf")) SaveImageAsEmf(filename);
361        else SaveImageAsBitmap(filename);
362      }
363    }
364
365    public void SaveImageAsBitmap(string filename) {
366      if (tree == null) return;
367      Image image = new Bitmap(Width, Height);
368      using (Graphics g = Graphics.FromImage(image)) {
369        int height = this.Height / tree.Depth;
370        DrawFunctionTree(tree, g, 0, 0, Width, height);
371      }
372      image.Save(filename);
373    }
374
375    public void SaveImageAsEmf(string filename) {
376      if (tree == null) return;
377      using (Graphics g = CreateGraphics()) {
378        using (Metafile file = new Metafile(filename, g.GetHdc())) {
379          using (Graphics emfFile = Graphics.FromImage(file)) {
380            int height = this.Height / tree.Depth;
381            DrawFunctionTree(tree, emfFile, 0, 0, Width, height);
382          }
383        }
384        g.ReleaseHdc();
385      }
386    }
387    #endregion
388    #region export pgf/tikz
389    private void exportLatexToolStripMenuItem_Click(object sender, EventArgs e) {
390      using (var dialog = new SaveFileDialog { Filter = "Tex (*.tex)|*.tex" }) {
391        if (dialog.ShowDialog() != DialogResult.OK) return;
392        string filename = dialog.FileName.ToLower();
393        var formatter = new SymbolicExpressionTreeLatexFormatter();
394        File.WriteAllText(filename, formatter.Format(Tree));
395      }
396    }
397    #endregion
398  }
399}
Note: See TracBrowser for help on using the repository browser.