Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMathematicaFormatter.cs @ 17869

Last change on this file since 17869 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

File size: 11.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Globalization;
24using System.Linq;
25using System.Text;
26using HEAL.Attic;
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.")]
33  [StorableType("818A9294-FA95-41F6-A5F0-D7D050BDD076")]
34  public sealed class SymbolicDataAnalysisExpressionMathematicaFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
35    [StorableConstructor]
36    private SymbolicDataAnalysisExpressionMathematicaFormatter(StorableConstructorFlag _) : base(_) { }
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 Absolute) {
59          FormatFunction(node, "Abs", strBuilder);
60        } else if (node.Symbol is AnalyticQuotient) {
61          strBuilder.Append("[");
62          FormatRecursively(node.GetSubtree(0), strBuilder);
63          strBuilder.Append("]/Sqrt[ 1 + Power[");
64          FormatRecursively(node.GetSubtree(1), strBuilder);
65          strBuilder.Append(", 2]]");
66        } else if (node.Symbol is Average) {
67          FormatAverage(node, strBuilder);
68        } else if (node.Symbol is Multiplication) {
69          FormatFunction(node, "Times", strBuilder);
70        } else if (node.Symbol is Subtraction) {
71          FormatSubtraction(node, strBuilder);
72        } else if (node.Symbol is Division) {
73          FormatDivision(node, strBuilder);
74        } else if (node.Symbol is Sine) {
75          FormatFunction(node, "Sin", strBuilder);
76        } else if (node.Symbol is Cosine) {
77          FormatFunction(node, "Cos", strBuilder);
78        } else if (node.Symbol is Tangent) {
79          FormatFunction(node, "Tan", strBuilder);
80        } else if (node.Symbol is HyperbolicTangent) {
81          FormatFunction(node, "Tanh", strBuilder);
82        } else if (node.Symbol is Exponential) {
83          FormatFunction(node, "Exp", strBuilder);
84        } else if (node.Symbol is Logarithm) {
85          FormatFunction(node, "Log", strBuilder);
86        } else if (node.Symbol is IfThenElse) {
87          FormatIf(node, strBuilder);
88        } else if (node.Symbol is GreaterThan) {
89          strBuilder.Append("If[Greater[");
90          FormatRecursively(node.GetSubtree(0), strBuilder);
91          strBuilder.Append(",");
92          FormatRecursively(node.GetSubtree(1), strBuilder);
93          strBuilder.Append("], 1, -1]");
94        } else if (node.Symbol is LessThan) {
95          strBuilder.Append("If[Less[");
96          FormatRecursively(node.GetSubtree(0), strBuilder);
97          strBuilder.Append(",");
98          FormatRecursively(node.GetSubtree(1), strBuilder);
99          strBuilder.Append("], 1, -1]");
100        } else if (node.Symbol is And) {
101          FormatAnd(node, strBuilder);
102        } else if (node.Symbol is Not) {
103          strBuilder.Append("If[Greater[");
104          FormatRecursively(node.GetSubtree(0), strBuilder);
105          strBuilder.Append(", 0], -1, 1]");
106        } else if (node.Symbol is Or) {
107          FormatOr(node, strBuilder);
108        } else if (node.Symbol is Xor) {
109          FormatXor(node, strBuilder);
110        } else if (node.Symbol is Square) {
111          FormatSquare(node, strBuilder);
112        } else if (node.Symbol is SquareRoot) {
113          FormatFunction(node, "Sqrt", strBuilder);
114        } else if (node.Symbol is Cube) {
115          FormatPower(node, strBuilder, "3");
116        } else if (node.Symbol is CubeRoot) {
117          strBuilder.Append("CubeRoot[");
118          FormatRecursively(node.GetSubtree(0), strBuilder);
119          strBuilder.Append("]");
120        } else if (node.Symbol is Power) {
121          FormatFunction(node, "Power", strBuilder);
122        } else if (node.Symbol is Root) {
123          FormatRoot(node, strBuilder);
124        } else {
125          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " is not supported.");
126        }
127      } else {
128        // terminals
129        if (node.Symbol is Variable) {
130          var varNode = node as VariableTreeNode;
131          strBuilder.AppendFormat("Times[{0}, {1}]", varNode.VariableName, varNode.Weight.ToString("G17", CultureInfo.InvariantCulture));
132        } else if (node.Symbol is Constant) {
133          var constNode = node as ConstantTreeNode;
134          strBuilder.Append(constNode.Value.ToString("G17", CultureInfo.InvariantCulture));
135        } else if (node.Symbol is FactorVariable) {
136          var factorNode = node as FactorVariableTreeNode;
137          strBuilder.AppendFormat("Switch[{0},", factorNode.VariableName);
138          var varValues = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray();
139          var weights = varValues.Select(factorNode.GetValue).ToArray();
140
141          var weightStr = string.Join(", ",
142            varValues.Zip(weights, (s, d) => string.Format(CultureInfo.InvariantCulture, "\"{0}\", {1:G17}", s, d)));
143          strBuilder.Append(weightStr);
144          strBuilder.Append("]");
145        } else if (node.Symbol is BinaryFactorVariable) {
146          var factorNode = node as BinaryFactorVariableTreeNode;
147          strBuilder.AppendFormat(CultureInfo.InvariantCulture, "If[{0}==\"{1}\",{2:G17},0.0]",
148            factorNode.VariableName, factorNode.VariableValue, factorNode.Weight);
149        } else {
150          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " is not supported.");
151        }
152      }
153    }
154
155    private void FormatXor(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
156      strBuilder.Append("If[Xor[");
157      foreach (var t in node.Subtrees) {
158        strBuilder.Append("Greater[");
159        FormatRecursively(t, strBuilder);
160        strBuilder.Append(", 0]");
161        if (t != node.Subtrees.Last()) strBuilder.Append(",");
162      }
163      strBuilder.Append("], 1, -1]");
164    }
165
166    private void FormatOr(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
167      strBuilder.Append("If[Or[");
168      foreach (var t in node.Subtrees) {
169        strBuilder.Append("Greater[");
170        FormatRecursively(t, strBuilder);
171        strBuilder.Append(", 0]");
172        if (t != node.Subtrees.Last()) strBuilder.Append(",");
173      }
174      strBuilder.Append("], 1, -1]");
175    }
176
177    private void FormatAnd(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
178      strBuilder.Append("If[And[");
179      foreach (var t in node.Subtrees) {
180        strBuilder.Append("Greater[");
181        FormatRecursively(t, strBuilder);
182        strBuilder.Append(", 0]");
183        if (t != node.Subtrees.Last()) strBuilder.Append(",");
184      }
185      strBuilder.Append("], 1, -1]");
186    }
187
188    private void FormatIf(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
189      strBuilder.Append("If[Greater[");
190      FormatRecursively(node.GetSubtree(0), strBuilder);
191      strBuilder.Append(", 0], ");
192      FormatRecursively(node.GetSubtree(1), strBuilder);
193      strBuilder.Append(", ");
194      FormatRecursively(node.GetSubtree(2), strBuilder);
195      strBuilder.Append("]");
196    }
197
198    private void FormatAverage(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
199      // mean function needs a list of values
200      strBuilder.Append("Mean[{");
201      FormatRecursively(node.GetSubtree(0), strBuilder);
202      for (int i = 1; i < node.SubtreeCount; i++) {
203        strBuilder.Append(",");
204        FormatRecursively(node.GetSubtree(i), strBuilder);
205      }
206      strBuilder.Append("}]");
207    }
208
209    private void FormatSubtraction(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
210      strBuilder.Append("Subtract[");
211      FormatRecursively(node.GetSubtree(0), strBuilder);
212      strBuilder.Append(", Times[-1");
213      foreach (var t in node.Subtrees) {
214        strBuilder.Append(",");
215        FormatRecursively(t, strBuilder);
216      }
217      strBuilder.Append("]]");
218    }
219
220    private void FormatSquare(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
221      FormatPower(node, strBuilder, "2");
222    }
223
224    private void FormatPower(ISymbolicExpressionTreeNode node, StringBuilder strBuilder, string exponent) {
225      strBuilder.Append("Power[");
226      FormatRecursively(node.GetSubtree(0), strBuilder);
227      strBuilder.Append($", {exponent}]");
228    }
229
230    private void FormatRoot(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
231      strBuilder.Append("Power[");
232      FormatRecursively(node.GetSubtree(0), strBuilder);
233      strBuilder.Append(", Divide[1,");
234      FormatRecursively(node.GetSubtree(1), strBuilder);
235      strBuilder.Append("]]");
236    }
237
238    private void FormatDivision(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
239      if (node.SubtreeCount == 1) {
240        strBuilder.Append("Divide[1, ");
241        FormatRecursively(node.GetSubtree(0), strBuilder);
242        strBuilder.Append("]");
243      } else {
244        strBuilder.Append("Divide[");
245        FormatRecursively(node.GetSubtree(0), strBuilder);
246        strBuilder.Append(", Times[");
247        FormatRecursively(node.GetSubtree(1), strBuilder);
248        for (int i = 2; i < node.SubtreeCount; i++) {
249          strBuilder.Append(",");
250          FormatRecursively(node.GetSubtree(i), strBuilder);
251        }
252        strBuilder.Append("]]");
253      }
254    }
255
256    private void FormatFunction(ISymbolicExpressionTreeNode node, string function, StringBuilder strBuilder) {
257      strBuilder.Append(function + "[");
258      foreach (var child in node.Subtrees) {
259        FormatRecursively(child, strBuilder);
260        if (child != node.Subtrees.Last())
261          strBuilder.Append(", ");
262      }
263      strBuilder.Append("]");
264    }
265  }
266}
Note: See TracBrowser for help on using the repository browser.