1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2016 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Globalization;
|
---|
25 | using System.Linq;
|
---|
26 | using System.Text;
|
---|
27 | using System.Text.RegularExpressions;
|
---|
28 | using HeuristicLab.Common;
|
---|
29 | using HeuristicLab.Core;
|
---|
30 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
31 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
32 |
|
---|
33 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
|
---|
34 | [Item("C# Symbolic Expression Tree Formatter", "A string formatter that converts symbolic expression trees to C# code.")]
|
---|
35 | [StorableClass]
|
---|
36 | public sealed class CSharpSymbolicExpressionTreeStringFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
|
---|
37 | [StorableConstructor]
|
---|
38 | private CSharpSymbolicExpressionTreeStringFormatter(bool deserializing) : base(deserializing) { }
|
---|
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 |
|
---|
58 | private string VariableName2Identifier(string name) {
|
---|
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 |
|
---|
96 | private void FormatRecursively(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
97 | // TODO: adapt to interpreter semantics. The HL interpreter also allows Boolean operations on reals
|
---|
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);
|
---|
125 | } else if (node.Symbol is Xor) {
|
---|
126 | FormatOperator(node, "^", strBuilder);
|
---|
127 | } else if (node.Symbol is Sine) {
|
---|
128 | FormatFunction(node, "Math.Sin", strBuilder);
|
---|
129 | } else if (node.Symbol is Subtraction) {
|
---|
130 | FormatSubtraction(node, strBuilder);
|
---|
131 | } else if (node.Symbol is Tangent) {
|
---|
132 | FormatFunction(node, "Math.Tan", strBuilder);
|
---|
133 | } else if (node.Symbol is Square) {
|
---|
134 | FormatSquare(node, strBuilder);
|
---|
135 | } else if (node.Symbol is SquareRoot) {
|
---|
136 | FormatFunction(node, "Math.Sqrt", strBuilder);
|
---|
137 | } else if (node.Symbol is Power) {
|
---|
138 | FormatFunction(node, "Math.Pow", strBuilder);
|
---|
139 | } else if (node.Symbol is Root) {
|
---|
140 | FormatRoot(node, strBuilder);
|
---|
141 | } else {
|
---|
142 | throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
|
---|
143 | }
|
---|
144 | } else {
|
---|
145 | if (node is VariableTreeNode) {
|
---|
146 | var varNode = node as VariableTreeNode;
|
---|
147 | strBuilder.AppendFormat("{0} * {1}", VariableName2Identifier(varNode.VariableName), varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));
|
---|
148 | } else if (node is ConstantTreeNode) {
|
---|
149 | var constNode = node as ConstantTreeNode;
|
---|
150 | strBuilder.Append(constNode.Value.ToString("g17", CultureInfo.InvariantCulture));
|
---|
151 | } else if (node.Symbol is FactorVariable) {
|
---|
152 | var factorNode = node as FactorVariableTreeNode;
|
---|
153 | FormatFactor(factorNode, strBuilder);
|
---|
154 | } else if (node.Symbol is BinaryFactorVariable) {
|
---|
155 | var binFactorNode = node as BinaryFactorVariableTreeNode;
|
---|
156 | FormatBinaryFactor(binFactorNode, strBuilder);
|
---|
157 | } else {
|
---|
158 | throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
|
---|
159 | }
|
---|
160 | }
|
---|
161 | }
|
---|
162 |
|
---|
163 | private void FormatFactor(FactorVariableTreeNode node, StringBuilder strBuilder) {
|
---|
164 | strBuilder.AppendFormat("EvaluateFactor({0}, new [] {{ {1} }}, new [] {{ {2} }})", VariableName2Identifier(node.VariableName),
|
---|
165 | string.Join(",", node.Symbol.GetVariableValues(node.VariableName).Select(name => "\"" + name + "\"")), string.Join(",", node.Weights.Select(v => v.ToString(CultureInfo.InvariantCulture))));
|
---|
166 | }
|
---|
167 |
|
---|
168 | private void FormatBinaryFactor(BinaryFactorVariableTreeNode node, StringBuilder strBuilder) {
|
---|
169 | strBuilder.AppendFormat(CultureInfo.InvariantCulture, "EvaluateBinaryFactor({0}, \"{1}\", {2})", VariableName2Identifier(node.VariableName), node.VariableValue, node.Weight);
|
---|
170 | }
|
---|
171 |
|
---|
172 | private void FormatSquare(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
173 | strBuilder.Append("Math.Pow(");
|
---|
174 | FormatRecursively(node.GetSubtree(0), strBuilder);
|
---|
175 | strBuilder.Append(", 2)");
|
---|
176 | }
|
---|
177 |
|
---|
178 | private void FormatRoot(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
179 | strBuilder.Append("Math.Pow(");
|
---|
180 | FormatRecursively(node.GetSubtree(0), strBuilder);
|
---|
181 | strBuilder.Append(", 1.0 / (");
|
---|
182 | FormatRecursively(node.GetSubtree(1), strBuilder);
|
---|
183 | strBuilder.Append("))");
|
---|
184 | }
|
---|
185 |
|
---|
186 | private void FormatDivision(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
187 | if (node.SubtreeCount == 1) {
|
---|
188 | strBuilder.Append("1.0 / ");
|
---|
189 | FormatRecursively(node.GetSubtree(0), strBuilder);
|
---|
190 | } else {
|
---|
191 | FormatRecursively(node.GetSubtree(0), strBuilder);
|
---|
192 | strBuilder.Append("/ (");
|
---|
193 | for (int i = 1; i < node.SubtreeCount; i++) {
|
---|
194 | if (i > 1) strBuilder.Append(" * ");
|
---|
195 | FormatRecursively(node.GetSubtree(i), strBuilder);
|
---|
196 | }
|
---|
197 | strBuilder.Append(")");
|
---|
198 | }
|
---|
199 | }
|
---|
200 |
|
---|
201 | private void FormatSubtraction(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
202 | if (node.SubtreeCount == 1) {
|
---|
203 | strBuilder.Append("-");
|
---|
204 | FormatRecursively(node.GetSubtree(0), strBuilder);
|
---|
205 | return;
|
---|
206 | }
|
---|
207 | //Default case: more than 1 child
|
---|
208 | FormatOperator(node, "-", strBuilder);
|
---|
209 | }
|
---|
210 |
|
---|
211 | private void FormatOperator(ISymbolicExpressionTreeNode node, string symbol, StringBuilder strBuilder) {
|
---|
212 | strBuilder.Append("(");
|
---|
213 | foreach (var child in node.Subtrees) {
|
---|
214 | FormatRecursively(child, strBuilder);
|
---|
215 | if (child != node.Subtrees.Last())
|
---|
216 | strBuilder.Append(" " + symbol + " ");
|
---|
217 | }
|
---|
218 | strBuilder.Append(")");
|
---|
219 | }
|
---|
220 |
|
---|
221 | private void FormatFunction(ISymbolicExpressionTreeNode node, string function, StringBuilder strBuilder) {
|
---|
222 | strBuilder.Append(function + "(");
|
---|
223 | foreach (var child in node.Subtrees) {
|
---|
224 | FormatRecursively(child, strBuilder);
|
---|
225 | if (child != node.Subtrees.Last())
|
---|
226 | strBuilder.Append(", ");
|
---|
227 | }
|
---|
228 | strBuilder.Append(")");
|
---|
229 | }
|
---|
230 |
|
---|
231 | private void GenerateHeader(StringBuilder strBuilder, ISymbolicExpressionTree symbolicExpressionTree) {
|
---|
232 | strBuilder.AppendLine("using System;");
|
---|
233 | strBuilder.AppendLine("using System.Linq;" + Environment.NewLine);
|
---|
234 | strBuilder.AppendLine("namespace HeuristicLab.Models {");
|
---|
235 | strBuilder.AppendLine("public static class Model {");
|
---|
236 | GenerateAverageSource(strBuilder);
|
---|
237 | GenerateIfThenElseSource(strBuilder);
|
---|
238 | GenerateFactorSource(strBuilder);
|
---|
239 | GenerateBinaryFactorSource(strBuilder);
|
---|
240 | strBuilder.Append(Environment.NewLine + "public static double Evaluate (");
|
---|
241 |
|
---|
242 | // 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
|
---|
243 | HashSet<string> doubleVarNames = new HashSet<string>();
|
---|
244 | foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode || x is VariableConditionTreeNode)) {
|
---|
245 | doubleVarNames.Add(((IVariableTreeNode)node).VariableName);
|
---|
246 | }
|
---|
247 |
|
---|
248 | HashSet<string> stringVarNames = new HashSet<string>();
|
---|
249 | foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is BinaryFactorVariableTreeNode || x is FactorVariableTreeNode)) {
|
---|
250 | stringVarNames.Add(((IVariableTreeNode)node).VariableName);
|
---|
251 | }
|
---|
252 |
|
---|
253 | var orderedNames = stringVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "string " + VariableName2Identifier(n) + " /* " + n + " */");
|
---|
254 | strBuilder.Append(string.Join(", ", orderedNames));
|
---|
255 |
|
---|
256 | if (stringVarNames.Any() && doubleVarNames.Any())
|
---|
257 | strBuilder.AppendLine(",");
|
---|
258 | orderedNames = doubleVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "double " + VariableName2Identifier(n) + " /* " + n + " */");
|
---|
259 | strBuilder.Append(string.Join(", ", orderedNames));
|
---|
260 |
|
---|
261 |
|
---|
262 | strBuilder.AppendLine(") {");
|
---|
263 | strBuilder.Append("double result = ");
|
---|
264 | }
|
---|
265 |
|
---|
266 | private void GenerateFooter(StringBuilder strBuilder) {
|
---|
267 | strBuilder.AppendLine(";");
|
---|
268 |
|
---|
269 | strBuilder.AppendLine("return result;");
|
---|
270 | strBuilder.AppendLine("}");
|
---|
271 | strBuilder.AppendLine("}");
|
---|
272 | strBuilder.AppendLine("}");
|
---|
273 | }
|
---|
274 |
|
---|
275 | private void GenerateAverageSource(StringBuilder strBuilder) {
|
---|
276 | strBuilder.AppendLine("private static double Average(params double[] values) {");
|
---|
277 | strBuilder.AppendLine(" return values.Average();");
|
---|
278 | strBuilder.AppendLine("}");
|
---|
279 | }
|
---|
280 |
|
---|
281 | private void GenerateIfThenElseSource(StringBuilder strBuilder) {
|
---|
282 | strBuilder.AppendLine("private static double EvaluateIf(bool condition, double then, double @else) {");
|
---|
283 | strBuilder.AppendLine(" return condition ? then : @else;");
|
---|
284 | strBuilder.AppendLine("}");
|
---|
285 | }
|
---|
286 |
|
---|
287 | private void GenerateFactorSource(StringBuilder strBuilder) {
|
---|
288 | strBuilder.AppendLine("private static double EvaluateFactor(string factorValue, string[] factorValues, double[] constants) {");
|
---|
289 | strBuilder.AppendLine(" for(int i=0;i<factorValues.Length;i++) " +
|
---|
290 | " if(factorValues[i] == factorValue) return constants[i];" +
|
---|
291 | " throw new ArgumentException();");
|
---|
292 | strBuilder.AppendLine("}");
|
---|
293 | }
|
---|
294 |
|
---|
295 | private void GenerateBinaryFactorSource(StringBuilder strBuilder) {
|
---|
296 | strBuilder.AppendLine("private static double EvaluateBinaryFactor(string factorValue, string targetValue, double weight) {");
|
---|
297 | strBuilder.AppendLine(" return factorValue == targetValue ? weight : 0.0;");
|
---|
298 | strBuilder.AppendLine("}");
|
---|
299 | }
|
---|
300 |
|
---|
301 | }
|
---|
302 | }
|
---|