Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionCSharpFormatter.cs

Last change on this file was 18220, checked in by gkronber, 3 years ago

#3136: reintegrated structure-template GP branch into trunk

File size: 15.3 KB
RevLine 
[12434]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[12434]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;
[14826]27using System.Text.RegularExpressions;
[16702]28using HEAL.Attic;
[12434]29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
34  [Item("C# Symbolic Expression Tree Formatter", "A string formatter that converts symbolic expression trees to C# code.")]
[16565]35  [StorableType("88298836-6087-405A-9354-D4E6864887EB")]
[12434]36  public sealed class CSharpSymbolicExpressionTreeStringFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
37    [StorableConstructor]
[16565]38    private CSharpSymbolicExpressionTreeStringFormatter(StorableConstructorFlag _) : base(_) { }
[12434]39    private CSharpSymbolicExpressionTreeStringFormatter(CSharpSymbolicExpressionTreeStringFormatter original, Cloner cloner) : base(original, cloner) { }
40    public CSharpSymbolicExpressionTreeStringFormatter()
41      : base() {
42      Name = ItemName;
43      Description = ItemDescription;
44    }
45    public override IDeepCloneable Clone(Cloner cloner) {
46      return new CSharpSymbolicExpressionTreeStringFormatter(this, cloner);
47    }
48
49    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
50      // skip root and start symbols
51      StringBuilder strBuilder = new StringBuilder();
52      GenerateHeader(strBuilder, symbolicExpressionTree);
53      FormatRecursively(symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0), strBuilder);
54      GenerateFooter(strBuilder);
55      return strBuilder.ToString();
56    }
57
[16702]58    private string VariableName2Identifier(string name) {
[14826]59      /*
60       * identifier-start-character:
61       *    letter-character
62       *    _ (the underscore character U+005F)
63       *  identifier-part-characters:
64       *    identifier-part-character
65       *    identifier-part-characters   identifier-part-character
66       *  identifier-part-character:
67       *    letter-character
68       *    decimal-digit-character
69       *    connecting-character
70       *    combining-character
71       *    formatting-character
72       *  letter-character:
73       *    A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl
74       *    A unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl
75       *  combining-character:
76       *    A Unicode character of classes Mn or Mc
77       *    A unicode-escape-sequence representing a character of classes Mn or Mc
78       *  decimal-digit-character:
79       *    A Unicode character of the class Nd
80       *    A unicode-escape-sequence representing a character of the class Nd
81       *  connecting-character:
82       *    A Unicode character of the class Pc
83       *    A unicode-escape-sequence representing a character of the class Pc
84       *  formatting-character:
85       *    A Unicode character of the class Cf
86       *    A unicode-escape-sequence representing a character of the class Cf
87       */
88
89      var invalidIdentifierStarts = new Regex(@"[^_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}]");
90      var invalidIdentifierParts = new Regex(@"[^\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]");
91      return "@" +
92        (invalidIdentifierStarts.IsMatch(name.Substring(0, 1)) ? "_" : "") + // prepend '_' if necessary
93        invalidIdentifierParts.Replace(name, "_");
94    }
95
[12434]96    private void FormatRecursively(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
[12982]97      // TODO: adapt to interpreter semantics. The HL interpreter also allows Boolean operations on reals
[12434]98      if (node.Subtrees.Any()) {
99        if (node.Symbol is Addition) {
100          FormatOperator(node, "+", strBuilder);
101        } else if (node.Symbol is And) {
102          FormatOperator(node, "&&", strBuilder);
103        } else if (node.Symbol is Average) {
104          FormatFunction(node, "Average", strBuilder);
105        } else if (node.Symbol is Cosine) {
106          FormatFunction(node, "Math.Cos", strBuilder);
107        } else if (node.Symbol is Division) {
108          FormatDivision(node, strBuilder);
109        } else if (node.Symbol is Exponential) {
110          FormatFunction(node, "Math.Exp", strBuilder);
111        } else if (node.Symbol is GreaterThan) {
112          FormatOperator(node, ">", strBuilder);
113        } else if (node.Symbol is IfThenElse) {
114          FormatFunction(node, "EvaluateIf", strBuilder);
115        } else if (node.Symbol is LessThan) {
116          FormatOperator(node, "<", strBuilder);
117        } else if (node.Symbol is Logarithm) {
118          FormatFunction(node, "Math.Log", strBuilder);
119        } else if (node.Symbol is Multiplication) {
120          FormatOperator(node, "*", strBuilder);
121        } else if (node.Symbol is Not) {
122          FormatOperator(node, "!", strBuilder);
123        } else if (node.Symbol is Or) {
124          FormatOperator(node, "||", strBuilder);
[12982]125        } else if (node.Symbol is Xor) {
126          FormatOperator(node, "^", strBuilder);
[12434]127        } else if (node.Symbol is Sine) {
128          FormatFunction(node, "Math.Sin", strBuilder);
129        } else if (node.Symbol is Subtraction) {
[13116]130          FormatSubtraction(node, strBuilder);
[12434]131        } else if (node.Symbol is Tangent) {
132          FormatFunction(node, "Math.Tan", strBuilder);
[16702]133        } else if (node.Symbol is HyperbolicTangent) {
134          FormatFunction(node, "Math.Tanh", strBuilder);
[12434]135        } else if (node.Symbol is Square) {
136          FormatSquare(node, strBuilder);
137        } else if (node.Symbol is SquareRoot) {
138          FormatFunction(node, "Math.Sqrt", strBuilder);
[16802]139        } else if (node.Symbol is Cube) {
140          FormatPower(node, strBuilder, "3");
141        } else if (node.Symbol is CubeRoot) {
[16905]142          strBuilder.Append("Cbrt(");
143          FormatRecursively(node.GetSubtree(0), strBuilder);
144          strBuilder.Append(")");
[12434]145        } else if (node.Symbol is Power) {
146          FormatFunction(node, "Math.Pow", strBuilder);
147        } else if (node.Symbol is Root) {
148          FormatRoot(node, strBuilder);
[16802]149        } else if (node.Symbol is Absolute) {
150          FormatFunction(node, "Math.Abs", strBuilder);
151        } else if (node.Symbol is AnalyticQuotient) {
152          strBuilder.Append("(");
153          FormatRecursively(node.GetSubtree(0), strBuilder);
154          strBuilder.Append(" / Math.Sqrt(1 + Math.Pow(");
155          FormatRecursively(node.GetSubtree(1), strBuilder);
[17648]156          strBuilder.Append(" , 2) ) )");
[18220]157        } else if (node.Symbol is SubFunctionSymbol) {
158          FormatRecursively(node.GetSubtree(0), strBuilder);
[12434]159        } else {
160          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
161        }
162      } else {
163        if (node is VariableTreeNode) {
164          var varNode = node as VariableTreeNode;
[14826]165          strBuilder.AppendFormat("{0} * {1}", VariableName2Identifier(varNode.VariableName), varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));
[18132]166        } else if (node is INumericTreeNode numNode) {
167          strBuilder.Append(numNode.Value.ToString("g17", CultureInfo.InvariantCulture));
[14826]168        } else if (node.Symbol is FactorVariable) {
169          var factorNode = node as FactorVariableTreeNode;
170          FormatFactor(factorNode, strBuilder);
171        } else if (node.Symbol is BinaryFactorVariable) {
172          var binFactorNode = node as BinaryFactorVariableTreeNode;
173          FormatBinaryFactor(binFactorNode, strBuilder);
[12434]174        } else {
175          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
176        }
177      }
178    }
179
[14826]180    private void FormatFactor(FactorVariableTreeNode node, StringBuilder strBuilder) {
181      strBuilder.AppendFormat("EvaluateFactor({0}, new [] {{ {1} }}, new [] {{ {2} }})", VariableName2Identifier(node.VariableName),
182        string.Join(",", node.Symbol.GetVariableValues(node.VariableName).Select(name => "\"" + name + "\"")), string.Join(",", node.Weights.Select(v => v.ToString(CultureInfo.InvariantCulture))));
183    }
184
185    private void FormatBinaryFactor(BinaryFactorVariableTreeNode node, StringBuilder strBuilder) {
186      strBuilder.AppendFormat(CultureInfo.InvariantCulture, "EvaluateBinaryFactor({0}, \"{1}\", {2})", VariableName2Identifier(node.VariableName), node.VariableValue, node.Weight);
187    }
188
[12434]189    private void FormatSquare(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
[16802]190      FormatPower(node, strBuilder, "2");
191    }
192    private void FormatPower(ISymbolicExpressionTreeNode node, StringBuilder strBuilder, string exponent) {
[12434]193      strBuilder.Append("Math.Pow(");
194      FormatRecursively(node.GetSubtree(0), strBuilder);
[16802]195      strBuilder.Append($", {exponent})");
[12434]196    }
197
198    private void FormatRoot(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
199      strBuilder.Append("Math.Pow(");
200      FormatRecursively(node.GetSubtree(0), strBuilder);
201      strBuilder.Append(", 1.0 / (");
202      FormatRecursively(node.GetSubtree(1), strBuilder);
203      strBuilder.Append("))");
204    }
205
206    private void FormatDivision(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
207      if (node.SubtreeCount == 1) {
208        strBuilder.Append("1.0 / ");
209        FormatRecursively(node.GetSubtree(0), strBuilder);
210      } else {
211        FormatRecursively(node.GetSubtree(0), strBuilder);
212        strBuilder.Append("/ (");
213        for (int i = 1; i < node.SubtreeCount; i++) {
214          if (i > 1) strBuilder.Append(" * ");
215          FormatRecursively(node.GetSubtree(i), strBuilder);
216        }
217        strBuilder.Append(")");
218      }
219    }
220
[13116]221    private void FormatSubtraction(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
222      if (node.SubtreeCount == 1) {
223        strBuilder.Append("-");
224        FormatRecursively(node.GetSubtree(0), strBuilder);
225        return;
226      }
227      //Default case: more than 1 child
228      FormatOperator(node, "-", strBuilder);
229    }
230
[12434]231    private void FormatOperator(ISymbolicExpressionTreeNode node, string symbol, StringBuilder strBuilder) {
232      strBuilder.Append("(");
233      foreach (var child in node.Subtrees) {
234        FormatRecursively(child, strBuilder);
235        if (child != node.Subtrees.Last())
236          strBuilder.Append(" " + symbol + " ");
237      }
238      strBuilder.Append(")");
239    }
240
241    private void FormatFunction(ISymbolicExpressionTreeNode node, string function, StringBuilder strBuilder) {
242      strBuilder.Append(function + "(");
243      foreach (var child in node.Subtrees) {
244        FormatRecursively(child, strBuilder);
245        if (child != node.Subtrees.Last())
246          strBuilder.Append(", ");
247      }
248      strBuilder.Append(")");
249    }
250
251    private void GenerateHeader(StringBuilder strBuilder, ISymbolicExpressionTree symbolicExpressionTree) {
252      strBuilder.AppendLine("using System;");
253      strBuilder.AppendLine("using System.Linq;" + Environment.NewLine);
254      strBuilder.AppendLine("namespace HeuristicLab.Models {");
255      strBuilder.AppendLine("public static class Model {");
256      GenerateAverageSource(strBuilder);
[16905]257      GenerateCbrtSource(strBuilder);
[12434]258      GenerateIfThenElseSource(strBuilder);
[14826]259      GenerateFactorSource(strBuilder);
260      GenerateBinaryFactorSource(strBuilder);
[12434]261      strBuilder.Append(Environment.NewLine + "public static double Evaluate (");
262
[14826]263      // here we don't have access to problemData to determine the type for each variable (double/string) therefore we must distinguish based on the symbol type
264      HashSet<string> doubleVarNames = new HashSet<string>();
265      foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode || x is VariableConditionTreeNode)) {
266        doubleVarNames.Add(((IVariableTreeNode)node).VariableName);
[12434]267      }
268
[14826]269      HashSet<string> stringVarNames = new HashSet<string>();
270      foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is BinaryFactorVariableTreeNode || x is FactorVariableTreeNode)) {
271        stringVarNames.Add(((IVariableTreeNode)node).VariableName);
272      }
273
274      var orderedNames = stringVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "string " + VariableName2Identifier(n) + " /* " + n + " */");
[12645]275      strBuilder.Append(string.Join(", ", orderedNames));
276
[14826]277      if (stringVarNames.Any() && doubleVarNames.Any())
278        strBuilder.AppendLine(",");
279      orderedNames = doubleVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "double " + VariableName2Identifier(n) + " /* " + n + " */");
280      strBuilder.Append(string.Join(", ", orderedNames));
281
282
[12434]283      strBuilder.AppendLine(") {");
284      strBuilder.Append("double result = ");
285    }
286
287    private void GenerateFooter(StringBuilder strBuilder) {
288      strBuilder.AppendLine(";");
[14826]289
[12434]290      strBuilder.AppendLine("return result;");
291      strBuilder.AppendLine("}");
292      strBuilder.AppendLine("}");
293      strBuilder.AppendLine("}");
294    }
295
296    private void GenerateAverageSource(StringBuilder strBuilder) {
297      strBuilder.AppendLine("private static double Average(params double[] values) {");
298      strBuilder.AppendLine("  return values.Average();");
299      strBuilder.AppendLine("}");
300    }
[16905]301    private void GenerateCbrtSource(StringBuilder strBuilder) {
302      strBuilder.AppendLine("private static double Cbrt(double x) {");
303      strBuilder.AppendLine("  return x < 0 ? -Math.Pow(-x, 1.0 / 3.0) : Math.Pow(x, 1.0 / 3.0);");
304      strBuilder.AppendLine("}");
305    }
[12434]306
307    private void GenerateIfThenElseSource(StringBuilder strBuilder) {
308      strBuilder.AppendLine("private static double EvaluateIf(bool condition, double then, double @else) {");
309      strBuilder.AppendLine("   return condition ? then : @else;");
310      strBuilder.AppendLine("}");
311    }
[14826]312
313    private void GenerateFactorSource(StringBuilder strBuilder) {
[18132]314      strBuilder.AppendLine("private static double EvaluateFactor(string factorValue, string[] factorValues, double[] parameters) {");
[14826]315      strBuilder.AppendLine("   for(int i=0;i<factorValues.Length;i++) " +
[18132]316                            "      if(factorValues[i] == factorValue) return parameters[i];" +
[14826]317                            "   throw new ArgumentException();");
318      strBuilder.AppendLine("}");
319    }
320
321    private void GenerateBinaryFactorSource(StringBuilder strBuilder) {
322      strBuilder.AppendLine("private static double EvaluateBinaryFactor(string factorValue, string targetValue, double weight) {");
323      strBuilder.AppendLine("  return factorValue == targetValue ? weight : 0.0;");
324      strBuilder.AppendLine("}");
325    }
326
[12434]327  }
328}
Note: See TracBrowser for help on using the repository browser.