Free cookie consent management tool by TermsFeed Policy Generator

source: branches/crossvalidation-2434/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionCSharpFormatter.cs @ 13599

Last change on this file since 13599 was 12645, checked in by gkronber, 9 years ago

#2396 changed ordering of parameters for variables in the C# formater for symbolic expressions

File size: 8.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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("C# Symbolic Expression Tree Formatter", "A string formatter that converts symbolic expression trees to C# code.")]
34  [StorableClass]
35  public sealed class CSharpSymbolicExpressionTreeStringFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
36    [StorableConstructor]
37    private CSharpSymbolicExpressionTreeStringFormatter(bool deserializing) : base(deserializing) { }
38    private CSharpSymbolicExpressionTreeStringFormatter(CSharpSymbolicExpressionTreeStringFormatter original, Cloner cloner) : base(original, cloner) { }
39    public CSharpSymbolicExpressionTreeStringFormatter()
40      : base() {
41      Name = ItemName;
42      Description = ItemDescription;
43    }
44    public override IDeepCloneable Clone(Cloner cloner) {
45      return new CSharpSymbolicExpressionTreeStringFormatter(this, cloner);
46    }
47
48    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
49      // skip root and start symbols
50      StringBuilder strBuilder = new StringBuilder();
51      GenerateHeader(strBuilder, symbolicExpressionTree);
52      FormatRecursively(symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0), strBuilder);
53      GenerateFooter(strBuilder);
54      return strBuilder.ToString();
55    }
56
57    private void FormatRecursively(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
58      if (node.Subtrees.Any()) {
59        if (node.Symbol is Addition) {
60          FormatOperator(node, "+", strBuilder);
61        } else if (node.Symbol is And) {
62          FormatOperator(node, "&&", strBuilder);
63        } else if (node.Symbol is Average) {
64          FormatFunction(node, "Average", strBuilder);
65        } else if (node.Symbol is Cosine) {
66          FormatFunction(node, "Math.Cos", strBuilder);
67        } else if (node.Symbol is Division) {
68          FormatDivision(node, strBuilder);
69        } else if (node.Symbol is Exponential) {
70          FormatFunction(node, "Math.Exp", strBuilder);
71        } else if (node.Symbol is GreaterThan) {
72          FormatOperator(node, ">", strBuilder);
73        } else if (node.Symbol is IfThenElse) {
74          FormatFunction(node, "EvaluateIf", strBuilder);
75        } else if (node.Symbol is LessThan) {
76          FormatOperator(node, "<", strBuilder);
77        } else if (node.Symbol is Logarithm) {
78          FormatFunction(node, "Math.Log", strBuilder);
79        } else if (node.Symbol is Multiplication) {
80          FormatOperator(node, "*", strBuilder);
81        } else if (node.Symbol is Not) {
82          FormatOperator(node, "!", strBuilder);
83        } else if (node.Symbol is Or) {
84          FormatOperator(node, "||", strBuilder);
85        } else if (node.Symbol is Sine) {
86          FormatFunction(node, "Math.Sin", strBuilder);
87        } else if (node.Symbol is Subtraction) {
88          FormatOperator(node, "-", strBuilder);
89        } else if (node.Symbol is Tangent) {
90          FormatFunction(node, "Math.Tan", strBuilder);
91        } else if (node.Symbol is Square) {
92          FormatSquare(node, strBuilder);
93        } else if (node.Symbol is SquareRoot) {
94          FormatFunction(node, "Math.Sqrt", strBuilder);
95        } else if (node.Symbol is Power) {
96          FormatFunction(node, "Math.Pow", strBuilder);
97        } else if (node.Symbol is Root) {
98          FormatRoot(node, strBuilder);
99        } else {
100          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
101        }
102      } else {
103        if (node is VariableTreeNode) {
104          var varNode = node as VariableTreeNode;
105          strBuilder.AppendFormat("{0} * {1}", varNode.VariableName, varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));
106        } else if (node is ConstantTreeNode) {
107          var constNode = node as ConstantTreeNode;
108          strBuilder.Append(constNode.Value.ToString("g17", CultureInfo.InvariantCulture));
109        } else {
110          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
111        }
112      }
113    }
114
115    private void FormatSquare(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
116      strBuilder.Append("Math.Pow(");
117      FormatRecursively(node.GetSubtree(0), strBuilder);
118      strBuilder.Append(", 2)");
119    }
120
121    private void FormatRoot(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
122      strBuilder.Append("Math.Pow(");
123      FormatRecursively(node.GetSubtree(0), strBuilder);
124      strBuilder.Append(", 1.0 / (");
125      FormatRecursively(node.GetSubtree(1), strBuilder);
126      strBuilder.Append("))");
127    }
128
129    private void FormatDivision(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
130      if (node.SubtreeCount == 1) {
131        strBuilder.Append("1.0 / ");
132        FormatRecursively(node.GetSubtree(0), strBuilder);
133      } else {
134        FormatRecursively(node.GetSubtree(0), strBuilder);
135        strBuilder.Append("/ (");
136        for (int i = 1; i < node.SubtreeCount; i++) {
137          if (i > 1) strBuilder.Append(" * ");
138          FormatRecursively(node.GetSubtree(i), strBuilder);
139        }
140        strBuilder.Append(")");
141      }
142    }
143
144    private void FormatOperator(ISymbolicExpressionTreeNode node, string symbol, StringBuilder strBuilder) {
145      strBuilder.Append("(");
146      foreach (var child in node.Subtrees) {
147        FormatRecursively(child, strBuilder);
148        if (child != node.Subtrees.Last())
149          strBuilder.Append(" " + symbol + " ");
150      }
151      strBuilder.Append(")");
152    }
153
154    private void FormatFunction(ISymbolicExpressionTreeNode node, string function, StringBuilder strBuilder) {
155      strBuilder.Append(function + "(");
156      foreach (var child in node.Subtrees) {
157        FormatRecursively(child, strBuilder);
158        if (child != node.Subtrees.Last())
159          strBuilder.Append(", ");
160      }
161      strBuilder.Append(")");
162    }
163
164    private void GenerateHeader(StringBuilder strBuilder, ISymbolicExpressionTree symbolicExpressionTree) {
165      strBuilder.AppendLine("using System;");
166      strBuilder.AppendLine("using System.Linq;" + Environment.NewLine);
167      strBuilder.AppendLine("namespace HeuristicLab.Models {");
168      strBuilder.AppendLine("public static class Model {");
169      GenerateAverageSource(strBuilder);
170      GenerateIfThenElseSource(strBuilder);
171      strBuilder.Append(Environment.NewLine + "public static double Evaluate (");
172
173      HashSet<string> varNames = new HashSet<string>();
174      foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode)) {
175        varNames.Add(((VariableTreeNode)node).VariableName);
176      }
177
178      var orderedNames = varNames.OrderBy(n => n, new NaturalStringComparer()).Select(n=> "double " + n);
179      strBuilder.Append(string.Join(", ", orderedNames));
180
181      strBuilder.AppendLine(") {");
182      strBuilder.Append("double result = ");
183    }
184
185    private void GenerateFooter(StringBuilder strBuilder) {
186      strBuilder.AppendLine(";");
187      strBuilder.AppendLine("return result;");
188      strBuilder.AppendLine("}");
189      strBuilder.AppendLine("}");
190      strBuilder.AppendLine("}");
191    }
192
193    private void GenerateAverageSource(StringBuilder strBuilder) {
194      strBuilder.AppendLine("private static double Average(params double[] values) {");
195      strBuilder.AppendLine("  return values.Average();");
196      strBuilder.AppendLine("}");
197    }
198
199    private void GenerateIfThenElseSource(StringBuilder strBuilder) {
200      strBuilder.AppendLine("private static double EvaluateIf(bool condition, double then, double @else) {");
201      strBuilder.AppendLine("   return condition ? then : @else;");
202      strBuilder.AppendLine("}");
203    }
204  }
205}
Note: See TracBrowser for help on using the repository browser.