Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMathematicaFormatter.cs @ 16713

Last change on this file since 16713 was 16702, checked in by bburlacu, 6 years ago

#2866: Add tanh to all formatters except the TSQLExpressionFormatter, since TSQL does not have a TANH function (could be approximated but ugly).

File size: 10.6 KB
RevLine 
[12982]1#region License Information
2/* HeuristicLab
[16565]3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[12982]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.Globalization;
24using System.Linq;
25using System.Text;
[16702]26using HEAL.Attic;
[12982]27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30
31namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
32  [Item("Mathematica Symbolic Expression Tree Formatter", "A string formatter that converts symbolic expression trees to Mathematica expressions.")]
[16565]33  [StorableType("818A9294-FA95-41F6-A5F0-D7D050BDD076")]
[12982]34  public sealed class SymbolicDataAnalysisExpressionMathematicaFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
35    [StorableConstructor]
[16565]36    private SymbolicDataAnalysisExpressionMathematicaFormatter(StorableConstructorFlag _) : base(_) { }
[12982]37    private SymbolicDataAnalysisExpressionMathematicaFormatter(SymbolicDataAnalysisExpressionMathematicaFormatter original, Cloner cloner) : base(original, cloner) { }
38    public SymbolicDataAnalysisExpressionMathematicaFormatter()
39      : base() {
40      Name = ItemName;
41      Description = ItemDescription;
42    }
43    public override IDeepCloneable Clone(Cloner cloner) {
44      return new SymbolicDataAnalysisExpressionMathematicaFormatter(this, cloner);
45    }
46
47    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
48      // skip root and start symbols
49      StringBuilder strBuilder = new StringBuilder();
50      FormatRecursively(symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0), strBuilder);
51      return strBuilder.ToString();
52    }
53
54    private void FormatRecursively(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
55      if (node.Subtrees.Any()) {
56        if (node.Symbol is Addition) {
57          FormatFunction(node, "Plus", strBuilder);
58        } else if (node.Symbol is Average) {
59          FormatAverage(node, strBuilder);
60        } else if (node.Symbol is Multiplication) {
61          FormatFunction(node, "Times", strBuilder);
62        } else if (node.Symbol is Subtraction) {
63          FormatSubtraction(node, strBuilder);
64        } else if (node.Symbol is Division) {
65          FormatDivision(node, strBuilder);
66        } else if (node.Symbol is Sine) {
67          FormatFunction(node, "Sin", strBuilder);
68        } else if (node.Symbol is Cosine) {
69          FormatFunction(node, "Cos", strBuilder);
70        } else if (node.Symbol is Tangent) {
71          FormatFunction(node, "Tan", strBuilder);
[16702]72        } else if (node.Symbol is HyperbolicTangent) {
73          FormatFunction(node, "Tanh", strBuilder);
[12982]74        } else if (node.Symbol is Exponential) {
75          FormatFunction(node, "Exp", strBuilder);
76        } else if (node.Symbol is Logarithm) {
77          FormatFunction(node, "Log", strBuilder);
78        } else if (node.Symbol is IfThenElse) {
79          FormatIf(node, strBuilder);
80        } else if (node.Symbol is GreaterThan) {
81          strBuilder.Append("If[Greater[");
82          FormatRecursively(node.GetSubtree(0), strBuilder);
83          strBuilder.Append(",");
84          FormatRecursively(node.GetSubtree(1), strBuilder);
85          strBuilder.Append("], 1, -1]");
86        } else if (node.Symbol is LessThan) {
87          strBuilder.Append("If[Less[");
88          FormatRecursively(node.GetSubtree(0), strBuilder);
89          strBuilder.Append(",");
90          FormatRecursively(node.GetSubtree(1), strBuilder);
91          strBuilder.Append("], 1, -1]");
92        } else if (node.Symbol is And) {
93          FormatAnd(node, strBuilder);
94        } else if (node.Symbol is Not) {
95          strBuilder.Append("If[Greater[");
96          FormatRecursively(node.GetSubtree(0), strBuilder);
97          strBuilder.Append(", 0], -1, 1]");
98        } else if (node.Symbol is Or) {
99          FormatOr(node, strBuilder);
100        } else if (node.Symbol is Xor) {
101          FormatXor(node, strBuilder);
102        } else if (node.Symbol is Square) {
103          FormatSquare(node, strBuilder);
104        } else if (node.Symbol is SquareRoot) {
105          FormatFunction(node, "Sqrt", strBuilder);
106        } else if (node.Symbol is Power) {
107          FormatFunction(node, "Power", strBuilder);
108        } else if (node.Symbol is Root) {
109          FormatRoot(node, strBuilder);
110        } else {
111          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " is not supported.");
112        }
113      } else {
[14826]114        // terminals
115        if (node.Symbol is Variable) {
[12982]116          var varNode = node as VariableTreeNode;
117          strBuilder.AppendFormat("Times[{0}, {1}]", varNode.VariableName, varNode.Weight.ToString("G17", CultureInfo.InvariantCulture));
[14826]118        } else if (node.Symbol is Constant) {
[12982]119          var constNode = node as ConstantTreeNode;
120          strBuilder.Append(constNode.Value.ToString("G17", CultureInfo.InvariantCulture));
[14826]121        } else if (node.Symbol is FactorVariable) {
122          var factorNode = node as FactorVariableTreeNode;
123          strBuilder.AppendFormat("Switch[{0},", factorNode.VariableName);
124          var varValues = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray();
125          var weights = varValues.Select(factorNode.GetValue).ToArray();
126
127          var weightStr = string.Join(", ",
128            varValues.Zip(weights, (s, d) => string.Format(CultureInfo.InvariantCulture, "\"{0}\", {1:G17}", s, d)));
129          strBuilder.Append(weightStr);
130          strBuilder.Append("]");
131        } else if (node.Symbol is BinaryFactorVariable) {
132          var factorNode = node as BinaryFactorVariableTreeNode;
133          strBuilder.AppendFormat(CultureInfo.InvariantCulture, "If[{0}==\"{1}\",{2:G17},0.0]",
134            factorNode.VariableName, factorNode.VariableValue, factorNode.Weight);
[12982]135        } else {
136          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " is not supported.");
137        }
138      }
139    }
140
141    private void FormatXor(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
142      strBuilder.Append("If[Xor[");
143      foreach (var t in node.Subtrees) {
144        strBuilder.Append("Greater[");
145        FormatRecursively(t, strBuilder);
146        strBuilder.Append(", 0]");
147        if (t != node.Subtrees.Last()) strBuilder.Append(",");
148      }
149      strBuilder.Append("], 1, -1]");
150    }
151
152    private void FormatOr(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
153      strBuilder.Append("If[Or[");
154      foreach (var t in node.Subtrees) {
155        strBuilder.Append("Greater[");
156        FormatRecursively(t, strBuilder);
157        strBuilder.Append(", 0]");
158        if (t != node.Subtrees.Last()) strBuilder.Append(",");
159      }
160      strBuilder.Append("], 1, -1]");
161    }
162
163    private void FormatAnd(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
164      strBuilder.Append("If[And[");
165      foreach (var t in node.Subtrees) {
166        strBuilder.Append("Greater[");
167        FormatRecursively(t, strBuilder);
168        strBuilder.Append(", 0]");
169        if (t != node.Subtrees.Last()) strBuilder.Append(",");
170      }
171      strBuilder.Append("], 1, -1]");
172    }
173
174    private void FormatIf(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
175      strBuilder.Append("If[Greater[");
176      FormatRecursively(node.GetSubtree(0), strBuilder);
177      strBuilder.Append(", 0], ");
178      FormatRecursively(node.GetSubtree(1), strBuilder);
179      strBuilder.Append(", ");
180      FormatRecursively(node.GetSubtree(2), strBuilder);
181      strBuilder.Append("]");
182    }
183
184    private void FormatAverage(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
185      // mean function needs a list of values
186      strBuilder.Append("Mean[{");
187      FormatRecursively(node.GetSubtree(0), strBuilder);
188      for (int i = 1; i < node.SubtreeCount; i++) {
189        strBuilder.Append(",");
190        FormatRecursively(node.GetSubtree(i), strBuilder);
191      }
192      strBuilder.Append("}]");
193    }
194
195    private void FormatSubtraction(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
196      strBuilder.Append("Subtract[");
197      FormatRecursively(node.GetSubtree(0), strBuilder);
198      strBuilder.Append(", Times[-1");
199      foreach (var t in node.Subtrees) {
200        strBuilder.Append(",");
201        FormatRecursively(t, strBuilder);
202      }
203      strBuilder.Append("]]");
204    }
205
206    private void FormatSquare(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
207      strBuilder.Append("Power[");
208      FormatRecursively(node.GetSubtree(0), strBuilder);
209      strBuilder.Append(", 2]");
210    }
211
212    private void FormatRoot(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
213      strBuilder.Append("Power[");
214      FormatRecursively(node.GetSubtree(0), strBuilder);
215      strBuilder.Append(", Divide[1,");
216      FormatRecursively(node.GetSubtree(1), strBuilder);
217      strBuilder.Append("]]");
218    }
219
220    private void FormatDivision(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
221      if (node.SubtreeCount == 1) {
222        strBuilder.Append("Divide[1, ");
223        FormatRecursively(node.GetSubtree(0), strBuilder);
224        strBuilder.Append("]");
225      } else {
226        strBuilder.Append("Divide[");
227        FormatRecursively(node.GetSubtree(0), strBuilder);
228        strBuilder.Append(", Times[");
229        FormatRecursively(node.GetSubtree(1), strBuilder);
230        for (int i = 2; i < node.SubtreeCount; i++) {
231          strBuilder.Append(",");
232          FormatRecursively(node.GetSubtree(i), strBuilder);
233        }
234        strBuilder.Append("]]");
235      }
236    }
237
238    private void FormatFunction(ISymbolicExpressionTreeNode node, string function, StringBuilder strBuilder) {
239      strBuilder.Append(function + "[");
240      foreach (var child in node.Subtrees) {
241        FormatRecursively(child, strBuilder);
242        if (child != node.Subtrees.Last())
243          strBuilder.Append(", ");
244      }
245      strBuilder.Append("]");
246    }
247  }
248}
Note: See TracBrowser for help on using the repository browser.