[3915] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[15973] | 3 | * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[3915] | 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 |
|
---|
| 22 | using System;
|
---|
| 23 | using System.Collections.Generic;
|
---|
| 24 | using System.Drawing;
|
---|
| 25 | using System.Linq;
|
---|
[15973] | 26 | using System.Threading.Tasks;
|
---|
[3915] | 27 | using System.Windows.Forms;
|
---|
| 28 | using HeuristicLab.Common;
|
---|
| 29 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
[4068] | 30 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
|
---|
[15973] | 31 | using HeuristicLab.MainForm;
|
---|
[3915] | 32 | using HeuristicLab.MainForm.WindowsForms;
|
---|
| 33 |
|
---|
[5699] | 34 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
|
---|
| 35 | public abstract partial class InteractiveSymbolicDataAnalysisSolutionSimplifierView : AsynchronousContentView {
|
---|
[9006] | 36 | private Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> foldedNodes;
|
---|
[11086] | 37 | private Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> changedNodes;
|
---|
[5699] | 38 | private Dictionary<ISymbolicExpressionTreeNode, double> nodeImpacts;
|
---|
[11086] | 39 |
|
---|
[15973] | 40 | private readonly ISymbolicDataAnalysisSolutionImpactValuesCalculator impactCalculator;
|
---|
| 41 |
|
---|
| 42 | private readonly IProgress progress = new Progress();
|
---|
| 43 |
|
---|
[9006] | 44 | private enum TreeState { Valid, Invalid }
|
---|
[11086] | 45 | private TreeState treeState;
|
---|
[3915] | 46 |
|
---|
[15973] | 47 | protected InteractiveSymbolicDataAnalysisSolutionSimplifierView(ISymbolicDataAnalysisSolutionImpactValuesCalculator impactCalculator) {
|
---|
[3915] | 48 | InitializeComponent();
|
---|
[9006] | 49 | foldedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
|
---|
[11086] | 50 | changedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
|
---|
[8946] | 51 | nodeImpacts = new Dictionary<ISymbolicExpressionTreeNode, double>();
|
---|
[3915] | 52 | this.Caption = "Interactive Solution Simplifier";
|
---|
[15973] | 53 | this.impactCalculator = impactCalculator;
|
---|
[11086] | 54 |
|
---|
| 55 | // initialize the tree modifier that will be used to perform edit operations over the tree
|
---|
| 56 | treeChart.ModifyTree = Modify;
|
---|
[3915] | 57 | }
|
---|
| 58 |
|
---|
[11086] | 59 | /// <summary>
|
---|
| 60 | /// Remove, Replace or Insert subtrees
|
---|
| 61 | /// </summary>
|
---|
| 62 | /// <param name="tree">The symbolic expression tree</param>
|
---|
| 63 | /// <param name="parent">The insertion point (ie, the parent node who will receive a new child)</param>
|
---|
| 64 | /// <param name="oldChild">The subtree to be replaced</param>
|
---|
| 65 | /// <param name="newChild">The replacement subtree</param>
|
---|
| 66 | /// <param name="removeSubtree">Flag used to indicate if whole subtrees should be removed (default behavior), or just the subtree root</param>
|
---|
| 67 | private void Modify(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode parent,
|
---|
| 68 | ISymbolicExpressionTreeNode oldChild, ISymbolicExpressionTreeNode newChild, bool removeSubtree = true) {
|
---|
| 69 | if (oldChild == null && newChild == null)
|
---|
| 70 | throw new ArgumentNullException("Cannot deduce operation type from the arguments. Please provide non null operands.");
|
---|
| 71 | if (oldChild == null) {
|
---|
| 72 | // insertion operation
|
---|
| 73 | parent.AddSubtree(newChild);
|
---|
| 74 | newChild.Parent = parent;
|
---|
| 75 | } else if (newChild == null) {
|
---|
| 76 | // removal operation
|
---|
| 77 | parent.RemoveSubtree(parent.IndexOfSubtree(oldChild));
|
---|
| 78 | if (!removeSubtree) {
|
---|
| 79 | for (int i = oldChild.SubtreeCount - 1; i >= 0; --i) {
|
---|
| 80 | var subtree = oldChild.GetSubtree(i);
|
---|
| 81 | oldChild.RemoveSubtree(i);
|
---|
| 82 | parent.AddSubtree(subtree);
|
---|
| 83 | }
|
---|
| 84 | }
|
---|
| 85 | } else {
|
---|
| 86 | // replacement operation
|
---|
| 87 | var replacementIndex = parent.IndexOfSubtree(oldChild);
|
---|
| 88 | parent.RemoveSubtree(replacementIndex);
|
---|
| 89 | parent.InsertSubtree(replacementIndex, newChild);
|
---|
| 90 | newChild.Parent = parent;
|
---|
| 91 | if (changedNodes.ContainsKey(oldChild)) {
|
---|
| 92 | changedNodes.Add(newChild, changedNodes[oldChild]); // so that on double click the original node is restored
|
---|
| 93 | changedNodes.Remove(oldChild);
|
---|
| 94 | } else {
|
---|
| 95 | changedNodes.Add(newChild, oldChild);
|
---|
| 96 | }
|
---|
| 97 | }
|
---|
| 98 | treeState = IsValid(tree) ? TreeState.Valid : TreeState.Invalid;
|
---|
| 99 | switch (treeState) {
|
---|
| 100 | case TreeState.Valid:
|
---|
| 101 | this.grpViewHost.Enabled = true;
|
---|
| 102 | UpdateModel(Content.Model.SymbolicExpressionTree);
|
---|
| 103 | break;
|
---|
| 104 | case TreeState.Invalid:
|
---|
| 105 | this.grpViewHost.Enabled = false;
|
---|
| 106 | break;
|
---|
| 107 | }
|
---|
| 108 | }
|
---|
| 109 |
|
---|
| 110 | // the optimizer always assumes 2 children for multiplication and addition nodes
|
---|
| 111 | // thus, we enforce that the tree stays valid so that the constant optimization won't throw an exception
|
---|
| 112 | // by returning 2 as the minimum allowed arity for addition and multiplication symbols
|
---|
| 113 | private readonly Func<ISymbol, int> GetMinArity = symbol => {
|
---|
| 114 | var min = symbol.MinimumArity;
|
---|
| 115 | if (symbol is Multiplication || symbol is Division) return Math.Max(2, min);
|
---|
| 116 | return min;
|
---|
| 117 | };
|
---|
| 118 | private bool IsValid(ISymbolicExpressionTree tree) {
|
---|
| 119 | treeChart.Tree = tree;
|
---|
| 120 | treeChart.Repaint();
|
---|
[15973] | 121 | // check if all nodes have a legal arity
|
---|
| 122 | var nodes = tree.IterateNodesPostfix().ToList();
|
---|
| 123 | bool valid = !nodes.Any(node => node.SubtreeCount < GetMinArity(node.Symbol) || node.SubtreeCount > node.Symbol.MaximumArity);
|
---|
| 124 |
|
---|
[11086] | 125 | if (valid) {
|
---|
[15973] | 126 | // check if all variables are contained in the dataset
|
---|
| 127 | var variables = new HashSet<string>(Content.ProblemData.Dataset.DoubleVariables);
|
---|
| 128 | valid = nodes.OfType<VariableTreeNode>().All(x => variables.Contains(x.VariableName));
|
---|
| 129 | }
|
---|
| 130 |
|
---|
| 131 | if (valid) {
|
---|
[11086] | 132 | btnOptimizeConstants.Enabled = true;
|
---|
| 133 | btnSimplify.Enabled = true;
|
---|
[11111] | 134 | treeStatusValue.Visible = false;
|
---|
[11086] | 135 | } else {
|
---|
| 136 | btnOptimizeConstants.Enabled = false;
|
---|
| 137 | btnSimplify.Enabled = false;
|
---|
[11111] | 138 | treeStatusValue.Visible = true;
|
---|
[11086] | 139 | }
|
---|
| 140 | this.Refresh();
|
---|
| 141 | return valid;
|
---|
| 142 | }
|
---|
| 143 |
|
---|
[5699] | 144 | public new ISymbolicDataAnalysisSolution Content {
|
---|
| 145 | get { return (ISymbolicDataAnalysisSolution)base.Content; }
|
---|
[3915] | 146 | set { base.Content = value; }
|
---|
| 147 | }
|
---|
| 148 |
|
---|
| 149 | protected override void RegisterContentEvents() {
|
---|
| 150 | base.RegisterContentEvents();
|
---|
[8946] | 151 | Content.ModelChanged += Content_Changed;
|
---|
| 152 | Content.ProblemDataChanged += Content_Changed;
|
---|
[10564] | 153 | treeChart.Repainted += treeChart_Repainted;
|
---|
[15973] | 154 | MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(grpSimplify, progress);
|
---|
[3915] | 155 | }
|
---|
| 156 | protected override void DeregisterContentEvents() {
|
---|
| 157 | base.DeregisterContentEvents();
|
---|
[8946] | 158 | Content.ModelChanged -= Content_Changed;
|
---|
| 159 | Content.ProblemDataChanged -= Content_Changed;
|
---|
[10564] | 160 | treeChart.Repainted -= treeChart_Repainted;
|
---|
[15973] | 161 | MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(grpSimplify, false);
|
---|
[3915] | 162 | }
|
---|
| 163 |
|
---|
[8946] | 164 | private void Content_Changed(object sender, EventArgs e) {
|
---|
| 165 | UpdateView();
|
---|
[3915] | 166 | }
|
---|
[5699] | 167 |
|
---|
[3915] | 168 | protected override void OnContentChanged() {
|
---|
| 169 | base.OnContentChanged();
|
---|
[9006] | 170 | foldedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
|
---|
[8946] | 171 | UpdateView();
|
---|
| 172 | viewHost.Content = this.Content;
|
---|
[3915] | 173 | }
|
---|
| 174 |
|
---|
[10564] | 175 | private void treeChart_Repainted(object sender, EventArgs e) {
|
---|
| 176 | if (nodeImpacts != null && nodeImpacts.Count > 0)
|
---|
| 177 | PaintNodeImpacts();
|
---|
| 178 | }
|
---|
| 179 |
|
---|
[15973] | 180 | private async void UpdateView() {
|
---|
[8946] | 181 | if (Content == null || Content.Model == null || Content.ProblemData == null) return;
|
---|
| 182 | var tree = Content.Model.SymbolicExpressionTree;
|
---|
[8990] | 183 | treeChart.Tree = tree.Root.SubtreeCount > 1 ? new SymbolicExpressionTree(tree.Root) : new SymbolicExpressionTree(tree.Root.GetSubtree(0).GetSubtree(0));
|
---|
[3915] | 184 |
|
---|
[15973] | 185 | progress.Start("Calculate Impact and Replacement Values ...");
|
---|
| 186 | var impactAndReplacementValues = await Task.Run(() => CalculateImpactAndReplacementValues(tree));
|
---|
| 187 | await Task.Delay(500); // wait for progressbar to finish animation
|
---|
[10492] | 188 | var replacementValues = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item2);
|
---|
[8946] | 189 | foreach (var pair in replacementValues.Where(pair => !(pair.Key is ConstantTreeNode))) {
|
---|
[9006] | 190 | foldedNodes[pair.Key] = MakeConstantTreeNode(pair.Value);
|
---|
[8946] | 191 | }
|
---|
[11086] | 192 | nodeImpacts = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item1);
|
---|
[15973] | 193 | progress.Finish();
|
---|
[8946] | 194 | PaintNodeImpacts();
|
---|
[3915] | 195 | }
|
---|
| 196 |
|
---|
[15973] | 197 | protected virtual Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>> CalculateImpactAndReplacementValues(ISymbolicExpressionTree tree) {
|
---|
| 198 | var impactAndReplacementValues = new Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>>();
|
---|
| 199 | foreach (var node in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
|
---|
| 200 | double impactValue, replacementValue, newQualityForImpactsCalculation;
|
---|
| 201 | impactCalculator.CalculateImpactAndReplacementValues(Content.Model, node, Content.ProblemData, Content.ProblemData.TrainingIndices, out impactValue, out replacementValue, out newQualityForImpactsCalculation);
|
---|
| 202 | double newProgressValue = progress.ProgressValue + 1.0 / (tree.Length - 2);
|
---|
| 203 | progress.ProgressValue = Math.Min(newProgressValue, 1);
|
---|
| 204 | impactAndReplacementValues.Add(node, new Tuple<double, double>(impactValue, replacementValue));
|
---|
| 205 | }
|
---|
| 206 | return impactAndReplacementValues;
|
---|
| 207 | }
|
---|
| 208 |
|
---|
[5717] | 209 | protected abstract void UpdateModel(ISymbolicExpressionTree tree);
|
---|
[3915] | 210 |
|
---|
[15973] | 211 | protected virtual ISymbolicExpressionTree OptimizeConstants(ISymbolicExpressionTree tree, IProgress progress) {
|
---|
| 212 | return tree;
|
---|
| 213 | }
|
---|
| 214 |
|
---|
[8946] | 215 | private static ConstantTreeNode MakeConstantTreeNode(double value) {
|
---|
| 216 | var constant = new Constant { MinValue = value - 1, MaxValue = value + 1 };
|
---|
| 217 | var constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
|
---|
[3915] | 218 | constantTreeNode.Value = value;
|
---|
| 219 | return constantTreeNode;
|
---|
| 220 | }
|
---|
| 221 |
|
---|
| 222 | private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
|
---|
[11086] | 223 | if (treeState == TreeState.Invalid) return;
|
---|
[10521] | 224 | var visualNode = (VisualTreeNode<ISymbolicExpressionTreeNode>)sender;
|
---|
[11086] | 225 | if (visualNode.Content == null) { throw new Exception("VisualNode content cannot be null."); }
|
---|
[10521] | 226 | var symbExprTreeNode = (SymbolicExpressionTreeNode)visualNode.Content;
|
---|
[11086] | 227 | var tree = Content.Model.SymbolicExpressionTree;
|
---|
[9006] | 228 | var parent = symbExprTreeNode.Parent;
|
---|
| 229 | int indexOfSubtree = parent.IndexOfSubtree(symbExprTreeNode);
|
---|
[11086] | 230 | if (changedNodes.ContainsKey(symbExprTreeNode)) {
|
---|
| 231 | // undo node change
|
---|
| 232 | parent.RemoveSubtree(indexOfSubtree);
|
---|
| 233 | var originalNode = changedNodes[symbExprTreeNode];
|
---|
| 234 | parent.InsertSubtree(indexOfSubtree, originalNode);
|
---|
| 235 | changedNodes.Remove(symbExprTreeNode);
|
---|
| 236 | } else if (foldedNodes.ContainsKey(symbExprTreeNode)) {
|
---|
| 237 | // undo node folding
|
---|
| 238 | SwitchNodeWithReplacementNode(parent, indexOfSubtree);
|
---|
| 239 | }
|
---|
| 240 | UpdateModel(tree);
|
---|
[3915] | 241 | }
|
---|
| 242 |
|
---|
[5729] | 243 | private void SwitchNodeWithReplacementNode(ISymbolicExpressionTreeNode parent, int subTreeIndex) {
|
---|
[5736] | 244 | ISymbolicExpressionTreeNode subTree = parent.GetSubtree(subTreeIndex);
|
---|
[9006] | 245 | if (foldedNodes.ContainsKey(subTree)) {
|
---|
[10799] | 246 | parent.RemoveSubtree(subTreeIndex);
|
---|
[9006] | 247 | var replacementNode = foldedNodes[subTree];
|
---|
[5736] | 248 | parent.InsertSubtree(subTreeIndex, replacementNode);
|
---|
[5729] | 249 | // exchange key and value
|
---|
[9006] | 250 | foldedNodes.Remove(subTree);
|
---|
| 251 | foldedNodes.Add(replacementNode, subTree);
|
---|
[5729] | 252 | }
|
---|
[5455] | 253 | }
|
---|
| 254 |
|
---|
[3915] | 255 | private void PaintNodeImpacts() {
|
---|
| 256 | var impacts = nodeImpacts.Values;
|
---|
| 257 | double max = impacts.Max();
|
---|
| 258 | double min = impacts.Min();
|
---|
[11086] | 259 | foreach (ISymbolicExpressionTreeNode treeNode in Content.Model.SymbolicExpressionTree.IterateNodesPostfix()) {
|
---|
[10521] | 260 | VisualTreeNode<ISymbolicExpressionTreeNode> visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
|
---|
[8946] | 261 |
|
---|
[4477] | 262 | if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
|
---|
[11086] | 263 | visualTree.ToolTip = visualTree.Content.ToString();
|
---|
[5729] | 264 | double impact = nodeImpacts[treeNode];
|
---|
[5722] | 265 |
|
---|
[5717] | 266 | // impact = 0 if no change
|
---|
| 267 | // impact < 0 if new solution is better
|
---|
| 268 | // impact > 0 if new solution is worse
|
---|
| 269 | if (impact < 0.0) {
|
---|
[5729] | 270 | // min is guaranteed to be < 0
|
---|
[5717] | 271 | visualTree.FillColor = Color.FromArgb((int)(impact / min * 255), Color.Red);
|
---|
[5729] | 272 | } else if (impact.IsAlmost(0.0)) {
|
---|
| 273 | visualTree.FillColor = Color.White;
|
---|
[5717] | 274 | } else {
|
---|
[5729] | 275 | // max is guaranteed to be > 0
|
---|
[5717] | 276 | visualTree.FillColor = Color.FromArgb((int)(impact / max * 255), Color.Green);
|
---|
| 277 | }
|
---|
[3915] | 278 | visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
|
---|
[9006] | 279 | var constantReplacementNode = foldedNodes[treeNode] as ConstantTreeNode;
|
---|
[5729] | 280 | if (constantReplacementNode != null) {
|
---|
| 281 | visualTree.ToolTip += Environment.NewLine + "Replacement value: " + constantReplacementNode.Value;
|
---|
| 282 | }
|
---|
[6108] | 283 | }
|
---|
[9043] | 284 | if (visualTree != null)
|
---|
[11086] | 285 | if (changedNodes.ContainsKey(treeNode)) {
|
---|
| 286 | visualTree.LineColor = Color.DodgerBlue;
|
---|
| 287 | } else if (treeNode is ConstantTreeNode && foldedNodes.ContainsKey(treeNode)) {
|
---|
[9043] | 288 | visualTree.LineColor = Color.DarkOrange;
|
---|
| 289 | }
|
---|
[3915] | 290 | }
|
---|
[8980] | 291 | treeChart.RepaintNodes();
|
---|
[3915] | 292 | }
|
---|
[3927] | 293 |
|
---|
| 294 | private void btnSimplify_Click(object sender, EventArgs e) {
|
---|
[15973] | 295 | var simplifiedExpressionTree = TreeSimplifier.Simplify(Content.Model.SymbolicExpressionTree);
|
---|
[5722] | 296 | UpdateModel(simplifiedExpressionTree);
|
---|
[3927] | 297 | }
|
---|
[6256] | 298 |
|
---|
[15973] | 299 | private async void btnOptimizeConstants_Click(object sender, EventArgs e) {
|
---|
| 300 | progress.Start("Optimizing Constants ...");
|
---|
| 301 | var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
|
---|
| 302 | var newTree = await Task.Run(() => OptimizeConstants(tree, progress));
|
---|
| 303 | await Task.Delay(500); // wait for progressbar to finish animation
|
---|
| 304 | UpdateModel(newTree); // UpdateModel calls Progress.Finish (via Content_Changed)
|
---|
| 305 | }
|
---|
[3915] | 306 | }
|
---|
| 307 | }
|
---|