Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2389-EpsLexicase/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarAllowedChildSymbolsControl.cs @ 15985

Last change on this file since 15985 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 16.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.Linq;
26using System.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.PluginInfrastructure;
30
31using VisualSymbolicExpressionTreeNode = HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views.VisualTreeNode<HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode>;
32
33namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
34  public sealed partial class SymbolicExpressionGrammarAllowedChildSymbolsControl : UserControl {
35    private ObservableList<ISymbolicExpressionTreeNode> selectedSymbolicExpressionTreeNodes;
36
37    public SymbolicExpressionGrammarAllowedChildSymbolsControl() {
38      InitializeComponent();
39      selectedSymbolicExpressionTreeNodes = new ObservableList<ISymbolicExpressionTreeNode>();
40    }
41
42    private ISymbolicExpressionGrammar grammar;
43    public ISymbolicExpressionGrammar Grammar {
44      get { return grammar; }
45      set {
46        if (grammar != value) {
47          if (grammar != null) DeregisterGrammarEvents();
48          grammar = value;
49          if (grammar != null) RegisterGrammarEvents();
50          OnGrammarChanged();
51        }
52      }
53    }
54
55    private ISymbol symbol;
56    public ISymbol Symbol {
57      get { return symbol; }
58      set {
59        if (symbol != value) {
60          if (value != null && grammar == null) throw new InvalidOperationException("grammar is null");
61          if (value != null && !grammar.ContainsSymbol(value)) throw new ArgumentException("grammar does not contain symbol.");
62          symbol = value;
63          OnSymbolChanged();
64        }
65      }
66    }
67
68    private void RegisterGrammarEvents() {
69      grammar.Changed += new EventHandler(Grammar_Changed);
70      grammar.ReadOnlyChanged += new EventHandler(Grammar_ReadOnlyChanged);
71    }
72    private void DeregisterGrammarEvents() {
73      grammar.Changed -= new EventHandler(Grammar_Changed);
74      grammar.ReadOnlyChanged -= new EventHandler(Grammar_ReadOnlyChanged);
75    }
76
77    private void Grammar_Changed(object sender, EventArgs e) {
78      if (Grammar == null) return;
79      if (Symbol == null) return;
80      if (Symbol != null && !Grammar.ContainsSymbol(Symbol)) Symbol = null;
81      else BuildAllowedChildSymbolsTree();
82    }
83
84    private void Grammar_ReadOnlyChanged(object sender, EventArgs e) {
85      if (InvokeRequired) Invoke((MethodInvoker)BuildAllowedChildSymbolsTree);
86      else BuildAllowedChildSymbolsTree();
87    }
88
89    private void OnGrammarChanged() {
90      if (Grammar == null) {
91        symbolicExpressionTreeChart.Tree = null;
92        Symbol = null;
93      }
94    }
95    private void OnSymbolChanged() {
96      if (Symbol == null) symbolicExpressionTreeChart.Tree = null;
97      else BuildAllowedChildSymbolsTree();
98    }
99
100    private void BuildAllowedChildSymbolsTree() {
101      if (Symbol == null) {
102        symbolicExpressionTreeChart.Tree = null;
103        return;
104      }
105
106      var tree = new SymbolicExpressionTree(new SymbolicExpressionTreeNode(Symbol));
107      if (Grammar.GetMaximumSubtreeCount(Symbol) > 0) {
108        for (int i = 0; i < Grammar.GetMaximumSubtreeCount(Symbol); i++) {
109          var node = new DummySymbol("Subtree " + i).CreateTreeNode();
110          var groupSymbols = grammar.GetAllowedChildSymbols(Symbol, i).OfType<GroupSymbol>().ToList();
111          foreach (var childSymbol in Grammar.GetAllowedChildSymbols(Symbol, i)) {
112            if (!groupSymbols.Any(g => g != childSymbol && g.Flatten().Contains(childSymbol)))
113              node.AddSubtree(new SymbolicExpressionTreeNode(childSymbol));
114          }
115          tree.Root.AddSubtree(node);
116        }
117      }
118      symbolicExpressionTreeChart.Tree = tree;
119      symbolicExpressionTreeChart.SuspendRepaint = true;
120      foreach (var subtreeNode in tree.Root.Subtrees) {
121        foreach (var allowedChildNode in subtreeNode.Subtrees) {
122          var visualLine = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNodeConnection(subtreeNode, allowedChildNode);
123          visualLine.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
124        }
125      }
126
127      for (int i = Grammar.GetMinimumSubtreeCount(symbol); i < Grammar.GetMaximumSubtreeCount(symbol); i++) {
128        var subtreeNode = tree.Root.GetSubtree(i);
129        var visualTreeNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(subtreeNode);
130        visualTreeNode.TextColor = Color.Gray;
131        visualTreeNode.LineColor = Color.LightGray;
132
133        var visualLine = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNodeConnection(tree.Root, subtreeNode);
134        visualLine.LineColor = Color.LightGray;
135
136        foreach (var allowedChildNode in subtreeNode.Subtrees) {
137          visualTreeNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(allowedChildNode);
138          visualTreeNode.TextColor = Color.Gray;
139          visualTreeNode.LineColor = Color.LightGray;
140
141          visualLine = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNodeConnection(subtreeNode, allowedChildNode);
142          visualLine.LineColor = Color.LightGray;
143        }
144      }
145      symbolicExpressionTreeChart.SuspendRepaint = false;
146      UpdateSelectedSymbolicExpressionTreeNodes();
147    }
148
149    private void UpdateSelectedSymbolicExpressionTreeNodes() {
150      foreach (var node in symbolicExpressionTreeChart.Tree.IterateNodesPrefix()) {
151        var visualNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(node);
152        if (!selectedSymbolicExpressionTreeNodes.Contains(node)) visualNode.FillColor = Color.White;
153        else visualNode.FillColor = Color.LightSteelBlue;
154      }
155      symbolicExpressionTreeChart.RepaintNodes();
156    }
157
158    private void symbolicExpressionTreeChart_SymbolicExpressionTreeNodeClicked(object sender, MouseEventArgs e) {
159      if (Grammar.ReadOnly) return;
160      if ((Control.ModifierKeys & Keys.Control) == 0)
161        selectedSymbolicExpressionTreeNodes.Clear();
162
163      VisualSymbolicExpressionTreeNode clickedNode = (VisualSymbolicExpressionTreeNode)sender;
164      var selectedNode = clickedNode.Content;
165      if (selectedNode.SubtreeCount == 0) {
166        if (!selectedSymbolicExpressionTreeNodes.Contains(selectedNode))
167          selectedSymbolicExpressionTreeNodes.Add(selectedNode);
168        else
169          selectedSymbolicExpressionTreeNodes.Remove(selectedNode);
170      }
171
172      UpdateSelectedSymbolicExpressionTreeNodes();
173    }
174
175    private void symbolicExpressionTreeChart_KeyDown(object sender, KeyEventArgs e) {
176      if (Grammar.ReadOnly) return;
177      if (e.KeyCode == Keys.Delete) {
178        var root = symbolicExpressionTreeChart.Tree.Root;
179        Grammar.StartGrammarManipulation();
180        foreach (var node in selectedSymbolicExpressionTreeNodes) {
181          int argIndex = root.IndexOfSubtree(node.Parent);
182          Grammar.RemoveAllowedChildSymbol(root.Symbol, node.Symbol, argIndex);
183        }
184
185        selectedSymbolicExpressionTreeNodes.Clear();
186        Grammar.FinishedGrammarManipulation();
187      }
188    }
189
190    #region drag & drop operations
191    private bool validDragOperation;
192    private void symbolicExpressionTreeChart_DragEnter(object sender, DragEventArgs e) {
193      validDragOperation = false;
194      if (Grammar.ReadOnly) return;
195
196      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
197      var symbol = data as ISymbol;
198      var symbols = data as IEnumerable<ISymbol>;
199      if (symbol != null && !(symbol is IReadOnlySymbol) && Grammar.ContainsSymbol(symbol)) validDragOperation = true;
200      else if (symbols != null && symbols.All(s => !(symbol is IReadOnlySymbol) && Grammar.ContainsSymbol(s))) validDragOperation = true;
201    }
202
203    private void symbolicExpressionTreeChart_DragOver(object sender, DragEventArgs e) {
204      e.Effect = DragDropEffects.None;
205      if (validDragOperation) {
206        Point coordinates = symbolicExpressionTreeChart.PointToClient(new Point(e.X, e.Y));
207        var visualNode = symbolicExpressionTreeChart.FindVisualSymbolicExpressionTreeNodeAt(coordinates.X, coordinates.Y);
208        if (visualNode != null) {
209          var node = visualNode.Content;
210          var root = symbolicExpressionTreeChart.Tree.Root;
211          if (node == root || node.Parent == root) e.Effect = DragDropEffects.Copy;
212        }
213      }
214    }
215
216    private void symbolicExpressionTreeChart_DragDrop(object sender, DragEventArgs e) {
217      Point coordinates = symbolicExpressionTreeChart.PointToClient(new Point(e.X, e.Y));
218      var node = symbolicExpressionTreeChart.FindVisualSymbolicExpressionTreeNodeAt(coordinates.X, coordinates.Y);
219      var root = symbolicExpressionTreeChart.Tree.Root;
220
221      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
222      var symbol = data as ISymbol;
223      var symbols = data as IEnumerable<ISymbol>;
224
225      if (node.Content == root) {
226        if (symbol != null)
227          Grammar.AddAllowedChildSymbol(root.Symbol, symbol);
228        else if (symbols != null)
229          foreach (var s in symbols) Grammar.AddAllowedChildSymbol(root.Symbol, s);
230      } else {
231        int argumentIndex = root.IndexOfSubtree(node.Content);
232        if (symbol != null)
233          Grammar.AddAllowedChildSymbol(root.Symbol, symbol, argumentIndex);
234        else if (symbols != null)
235          foreach (var s in symbols) Grammar.AddAllowedChildSymbol(root.Symbol, s, argumentIndex);
236      }
237      BuildAllowedChildSymbolsTree();
238    }
239    #endregion
240
241    #region draw and handle root node with buttons to manipulate the subtree count
242    private RectangleF increaseMinimumSubtreeCountRectangle;
243    private RectangleF decreaseMinimumSubtreeCountRectangle;
244    private RectangleF increaseMaximumSubtreeCountRectangle;
245    private RectangleF decreaseMaximumSubtreeCountRectangle;
246    private void allowedChildSymbolsControl_Paint(object sender, PaintEventArgs e) {
247      increaseMinimumSubtreeCountRectangle = RectangleF.Empty;
248      decreaseMinimumSubtreeCountRectangle = RectangleF.Empty;
249      increaseMaximumSubtreeCountRectangle = RectangleF.Empty;
250      decreaseMaximumSubtreeCountRectangle = RectangleF.Empty;
251
252      if (Grammar == null) return;
253      if (symbolicExpressionTreeChart.Tree == null) return;
254
255      var rootNode = symbolicExpressionTreeChart.Tree.Root;
256      var visualRootNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(rootNode);
257      var graphics = e.Graphics;
258
259      if (rootNode.Symbol is IReadOnlySymbol) return;
260      if (rootNode.Symbol.MinimumArity == rootNode.Symbol.MaximumArity) return;
261
262      using (Pen pen = new Pen(Color.Black)) {
263        using (Font font = new Font("Times New Roman", 8)) {
264          var stringFormat = new StringFormat();
265          stringFormat.Alignment = StringAlignment.Center;
266          stringFormat.LineAlignment = StringAlignment.Center;
267          int spacing = 5;
268          int size = (visualRootNode.Height - spacing * 3) / 2;
269
270          increaseMinimumSubtreeCountRectangle = new RectangleF(visualRootNode.X - spacing - size, visualRootNode.Y + spacing, size, size);
271          decreaseMinimumSubtreeCountRectangle = new RectangleF(visualRootNode.X - spacing - size, visualRootNode.Y + size + 2 * spacing, size, size);
272          increaseMaximumSubtreeCountRectangle = new RectangleF(visualRootNode.X + visualRootNode.Width + spacing, visualRootNode.Y + spacing, size, size);
273          decreaseMaximumSubtreeCountRectangle = new RectangleF(visualRootNode.X + visualRootNode.Width + spacing, visualRootNode.Y + size + 2 * spacing, size, size);
274
275          pen.Color = Grammar.ReadOnly || Grammar.GetMaximumSubtreeCount(rootNode.Symbol) == Grammar.GetMinimumSubtreeCount(rootNode.Symbol) ? Color.LightGray : Color.Black;
276          graphics.DrawString("+", font, pen.Brush, increaseMinimumSubtreeCountRectangle, stringFormat);
277          graphics.DrawRectangle(pen, Rectangle.Round(increaseMinimumSubtreeCountRectangle));
278          if (pen.Color == Color.LightGray) increaseMinimumSubtreeCountRectangle = RectangleF.Empty;
279
280          pen.Color = Grammar.ReadOnly || Grammar.GetMinimumSubtreeCount(rootNode.Symbol) == rootNode.Symbol.MinimumArity ? Color.LightGray : Color.Black;
281          graphics.DrawString("-", font, pen.Brush, decreaseMinimumSubtreeCountRectangle, stringFormat);
282          graphics.DrawRectangle(pen, Rectangle.Round(decreaseMinimumSubtreeCountRectangle));
283          if (pen.Color == Color.LightGray) decreaseMinimumSubtreeCountRectangle = RectangleF.Empty;
284
285          pen.Color = Grammar.ReadOnly || Grammar.GetMaximumSubtreeCount(rootNode.Symbol) == rootNode.Symbol.MaximumArity ? Color.LightGray : Color.Black;
286          graphics.DrawRectangle(pen, Rectangle.Round(increaseMaximumSubtreeCountRectangle));
287          graphics.DrawString("+", font, pen.Brush, increaseMaximumSubtreeCountRectangle, stringFormat);
288          if (pen.Color == Color.LightGray) increaseMaximumSubtreeCountRectangle = RectangleF.Empty;
289
290          pen.Color = Grammar.ReadOnly || Grammar.GetMaximumSubtreeCount(rootNode.Symbol) == Grammar.GetMinimumSubtreeCount(rootNode.Symbol) ? Color.LightGray : Color.Black;
291          graphics.DrawRectangle(pen, Rectangle.Round(decreaseMaximumSubtreeCountRectangle));
292          graphics.DrawString("-", font, pen.Brush, decreaseMaximumSubtreeCountRectangle, stringFormat);
293          if (pen.Color == Color.LightGray) decreaseMaximumSubtreeCountRectangle = RectangleF.Empty;
294        }
295      }
296    }
297
298    private void allowedChildSymbolsControl_MouseDown(object sender, MouseEventArgs e) {
299      if (Grammar == null || Grammar.ReadOnly) return;
300      if (symbolicExpressionTreeChart.Tree == null) return;
301
302      var pointF = new PointF(e.X, e.Y);
303      var rootSymbol = symbolicExpressionTreeChart.Tree.Root.Symbol;
304      int minimumSubtreeCount = Grammar.GetMinimumSubtreeCount(rootSymbol);
305      int maximumSubtreecount = Grammar.GetMaximumSubtreeCount(rootSymbol);
306
307      bool changed = true;
308      if (increaseMinimumSubtreeCountRectangle.Contains(pointF))
309        Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount + 1, maximumSubtreecount);
310      else if (decreaseMinimumSubtreeCountRectangle.Contains(pointF))
311        Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount - 1, maximumSubtreecount);
312      else if (increaseMaximumSubtreeCountRectangle.Contains(pointF))
313        Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount, maximumSubtreecount + 1);
314      else if (decreaseMaximumSubtreeCountRectangle.Contains(pointF))
315        Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount, maximumSubtreecount - 1);
316      else
317        changed = false;
318
319      if (changed) BuildAllowedChildSymbolsTree();
320    }
321    #endregion
322
323  }
324
325  [NonDiscoverableType]
326  internal class DummySymbol : Symbol {
327    private const int minimumArity = 1;
328    private const int maximumArity = byte.MaxValue;
329
330    public override int MinimumArity {
331      get { return minimumArity; }
332    }
333    public override int MaximumArity {
334      get { return maximumArity; }
335    }
336
337    public DummySymbol(DummySymbol original, Cloner cloner) : base(original, cloner) { }
338    public DummySymbol(string name) : base(name, "DummySymbol for views") { }
339    public override IDeepCloneable Clone(Cloner cloner) { return new DummySymbol(this, cloner); }
340  }
341}
Note: See TracBrowser for help on using the repository browser.