source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionExcelFormatter.cs @ 17055

Last change on this file since 17055 was 17055, checked in by abeham, 2 years ago

#3001: merged to stable

File size: 14.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.Globalization;
25using System.Linq;
26using System.Text;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [Item("Excel String Formatter", "String formatter for string representations of symbolic data analysis expressions in Excel syntax.")]
34  [StorableClass]
35  public sealed class SymbolicDataAnalysisExpressionExcelFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
36    [StorableConstructor]
37    private SymbolicDataAnalysisExpressionExcelFormatter(bool deserializing) : base(deserializing) { }
38    private SymbolicDataAnalysisExpressionExcelFormatter(SymbolicDataAnalysisExpressionExcelFormatter original, Cloner cloner) : base(original, cloner) { }
39    public SymbolicDataAnalysisExpressionExcelFormatter()
40      : base() {
41      Name = ItemName;
42      Description = ItemDescription;
43    }
44    public override IDeepCloneable Clone(Cloner cloner) {
45      return new SymbolicDataAnalysisExpressionExcelFormatter(this, cloner);
46    }
47    private string GetExcelColumnName(int columnNumber) {
48      int dividend = columnNumber;
49      string columnName = String.Empty;
50
51      while (dividend > 0) {
52        int modulo = (dividend - 1) % 26;
53        columnName = System.Convert.ToChar(65 + modulo) + columnName;
54        dividend = (int)((dividend - modulo) / 26);
55      }
56
57      return columnName;
58    }
59
60    private readonly Dictionary<string, string> variableNameMapping = new Dictionary<string, string>();
61    private int currentVariableIndex = 0;
62    private string GetColumnToVariableName(string varName) {
63      if (!variableNameMapping.ContainsKey(varName)) {
64        currentVariableIndex++;
65        variableNameMapping.Add(varName, GetExcelColumnName(currentVariableIndex));
66      }
67      return string.Format("${0}1", variableNameMapping[varName]);
68    }
69    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
70      return Format(symbolicExpressionTree, null);
71    }
72
73
74    public string Format(ISymbolicExpressionTree symbolicExpressionTree, IDataset dataset) {
75      if (dataset != null)
76        return FormatWithMapping(symbolicExpressionTree, CalculateVariableMapping(symbolicExpressionTree, dataset));
77      else return FormatWithMapping(symbolicExpressionTree, new Dictionary<string, string>());
78    }
79
80    public string FormatWithMapping(ISymbolicExpressionTree symbolicExpressionTree, Dictionary<string, string> variableNameMapping) {
81      foreach (var kvp in variableNameMapping) this.variableNameMapping.Add(kvp.Key, kvp.Value);
82      var stringBuilder = new StringBuilder();
83
84      stringBuilder.Append("=");
85      stringBuilder.Append(FormatRecursively(symbolicExpressionTree.Root));
86
87      foreach (var variable in this.variableNameMapping) {
88        stringBuilder.AppendLine();
89        stringBuilder.Append(variable.Key + " = " + variable.Value);
90      }
91      return stringBuilder.ToString();
92    }
93
94    private Dictionary<string, string> CalculateVariableMapping(ISymbolicExpressionTree tree, IDataset dataset) {
95      var mapping = new Dictionary<string, string>();
96      int inputIndex = 0;
97      var usedVariables = tree.IterateNodesPrefix().OfType<IVariableTreeNode>().Select(v => v.VariableName).Distinct().ToArray();
98      foreach (var variable in dataset.VariableNames) {
99        if (!usedVariables.Contains(variable)) continue;
100        inputIndex++;
101        mapping[variable] = GetExcelColumnName(inputIndex);
102      }
103      return mapping;
104    }
105
106    private string FormatRecursively(ISymbolicExpressionTreeNode node) {
107      ISymbol symbol = node.Symbol;
108      StringBuilder stringBuilder = new StringBuilder();
109
110      if (symbol is ProgramRootSymbol) {
111        stringBuilder.AppendLine(FormatRecursively(node.GetSubtree(0)));
112      } else if (symbol is StartSymbol)
113        return FormatRecursively(node.GetSubtree(0));
114      else if (symbol is Addition) {
115        stringBuilder.Append("(");
116        for (int i = 0; i < node.SubtreeCount; i++) {
117          if (i > 0) stringBuilder.Append("+");
118          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
119        }
120        stringBuilder.Append(")");
121      } else if (symbol is Average) {
122        stringBuilder.Append("(1/(");
123        stringBuilder.Append(node.SubtreeCount);
124        stringBuilder.Append(")*(");
125        for (int i = 0; i < node.SubtreeCount; i++) {
126          if (i > 0) stringBuilder.Append("+");
127          stringBuilder.Append("(");
128          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
129          stringBuilder.Append(")");
130        }
131        stringBuilder.Append("))");
132      } else if (symbol is Constant) {
133        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
134        stringBuilder.Append(constantTreeNode.Value.ToString(CultureInfo.InvariantCulture));
135      } else if (symbol is Cosine) {
136        stringBuilder.Append("COS(");
137        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
138        stringBuilder.Append(")");
139      } else if (symbol is Division) {
140        if (node.SubtreeCount == 1) {
141          stringBuilder.Append("1/(");
142          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
143          stringBuilder.Append(")");
144        } else {
145          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
146          stringBuilder.Append("/(");
147          for (int i = 1; i < node.SubtreeCount; i++) {
148            if (i > 1) stringBuilder.Append("*");
149            stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
150          }
151          stringBuilder.Append(")");
152        }
153      } else if (symbol is Exponential) {
154        stringBuilder.Append("EXP(");
155        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
156        stringBuilder.Append(")");
157      } else if (symbol is Square) {
158        stringBuilder.Append("POWER(");
159        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
160        stringBuilder.Append(",2)");
161      } else if (symbol is SquareRoot) {
162        stringBuilder.Append("SQRT(");
163        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
164        stringBuilder.Append(")");
165      } else if (symbol is Logarithm) {
166        stringBuilder.Append("LN(");
167        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
168        stringBuilder.Append(")");
169      } else if (symbol is Multiplication) {
170        for (int i = 0; i < node.SubtreeCount; i++) {
171          if (i > 0) stringBuilder.Append("*");
172          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
173        }
174      } else if (symbol is Sine) {
175        stringBuilder.Append("SIN(");
176        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
177        stringBuilder.Append(")");
178      } else if (symbol is Subtraction) {
179        stringBuilder.Append("(");
180        if (node.SubtreeCount == 1) {
181          stringBuilder.Append("-");
182          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
183        } else {
184          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
185          for (int i = 1; i < node.SubtreeCount; i++) {
186            stringBuilder.Append("-");
187            stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
188          }
189        }
190        stringBuilder.Append(")");
191      } else if (symbol is Tangent) {
192        stringBuilder.Append("TAN(");
193        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
194        stringBuilder.Append(")");
195
196      } else if (symbol is Variable) {
197        VariableTreeNode variableTreeNode = node as VariableTreeNode;
198        stringBuilder.Append(variableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
199        stringBuilder.Append("*");
200        stringBuilder.Append(GetColumnToVariableName(variableTreeNode.VariableName));
201      } else if (symbol is BinaryFactorVariable) {
202        var binFactorNode = node as BinaryFactorVariableTreeNode;
203        stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, 0)",
204          GetColumnToVariableName(binFactorNode.VariableName),
205          binFactorNode.VariableValue,
206          binFactorNode.Weight.ToString(CultureInfo.InvariantCulture)
207          );
208      } else if (symbol is FactorVariable) {
209        var factorNode = node as FactorVariableTreeNode;
210        var values = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray();
211        var w = factorNode.Weights;
212        // create nested if
213        for (int i = 0; i < values.Length; i++) {
214          stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, ",
215            GetColumnToVariableName(factorNode.VariableName),
216            values[i],
217            w[i].ToString(CultureInfo.InvariantCulture));
218        }
219        stringBuilder.Append("\"\""); // return empty string on unknown value
220        stringBuilder.Append(')', values.Length); // add closing parenthesis
221      } else if (symbol is Power) {
222        stringBuilder.Append("POWER(");
223        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
224        stringBuilder.Append(",ROUND(");
225        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
226        stringBuilder.Append(",0))");
227      } else if (symbol is Root) {
228        stringBuilder.Append("(");
229        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
230        stringBuilder.Append(")^(1 / ROUND(");
231        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
232        stringBuilder.Append(",0))");
233      } else if (symbol is IfThenElse) {
234        stringBuilder.Append("IF(");
235        stringBuilder.Append("(" + FormatRecursively(node.GetSubtree(0)) + " ) > 0");
236        stringBuilder.Append(",");
237        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
238        stringBuilder.Append(",");
239        stringBuilder.Append(FormatRecursively(node.GetSubtree(2)));
240        stringBuilder.Append(")");
241      } else if (symbol is VariableCondition) {
242        VariableConditionTreeNode variableConditionTreeNode = node as VariableConditionTreeNode;
243        if (!variableConditionTreeNode.Symbol.IgnoreSlope) {
244          double threshold = variableConditionTreeNode.Threshold;
245          double slope = variableConditionTreeNode.Slope;
246          string p = "(1 / (1 + EXP(-" + slope.ToString(CultureInfo.InvariantCulture) + " * (" +
247                     GetColumnToVariableName(variableConditionTreeNode.VariableName) + "-" +
248                     threshold.ToString(CultureInfo.InvariantCulture) + "))))";
249          stringBuilder.Append("((");
250          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
251          stringBuilder.Append("*");
252          stringBuilder.Append(p);
253          stringBuilder.Append(") + (");
254          stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
255          stringBuilder.Append("*(");
256          stringBuilder.Append("1 - " + p + ")");
257          stringBuilder.Append("))");
258        } else {
259          stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "(IF({0} <= {1}, {2}, {3}))",
260            GetColumnToVariableName(variableConditionTreeNode.VariableName),
261            variableConditionTreeNode.Threshold,
262            FormatRecursively(node.GetSubtree(0)),
263            FormatRecursively(node.GetSubtree(1))
264            );
265        }
266      } else if (symbol is Xor) {
267        stringBuilder.Append("IF(");
268        stringBuilder.Append("XOR(");
269        stringBuilder.Append("(" + FormatRecursively(node.GetSubtree(0)) + ") > 0,");
270        stringBuilder.Append("(" + FormatRecursively(node.GetSubtree(1)) + ") > 0");
271        stringBuilder.Append("), 1.0, -1.0)");
272      } else if (symbol is Or) {
273        stringBuilder.Append("IF(");
274        stringBuilder.Append("OR(");
275        stringBuilder.Append("(" + FormatRecursively(node.GetSubtree(0)) + ") > 0,");
276        stringBuilder.Append("(" + FormatRecursively(node.GetSubtree(1)) + ") > 0");
277        stringBuilder.Append("), 1.0, -1.0)");
278      } else if (symbol is And) {
279        stringBuilder.Append("IF(");
280        stringBuilder.Append("AND(");
281        stringBuilder.Append("(" + FormatRecursively(node.GetSubtree(0)) + ") > 0,");
282        stringBuilder.Append("(" + FormatRecursively(node.GetSubtree(1)) + ") > 0");
283        stringBuilder.Append("), 1.0, -1.0)");
284      } else if (symbol is Not) {
285        stringBuilder.Append("IF(");
286        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
287        stringBuilder.Append(" > 0, -1.0, 1.0)");
288      } else if (symbol is GreaterThan) {
289        stringBuilder.Append("IF((");
290        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
291        stringBuilder.Append(") > (");
292        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
293        stringBuilder.Append("), 1.0, -1.0)");
294      } else if (symbol is LessThan) {
295        stringBuilder.Append("IF((");
296        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
297        stringBuilder.Append(") < (");
298        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
299        stringBuilder.Append("), 1.0, -1.0)");
300      } else {
301        throw new NotImplementedException("Excel export of " + node.Symbol + " is not implemented.");
302      }
303      return stringBuilder.ToString();
304    }
305  }
306}
Note: See TracBrowser for help on using the repository browser.