source: branches/2911_TSQLSymbolicExpressionFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/TSQLExpressionFormatter.cs @ 15877

Last change on this file since 15877 was 15877, checked in by fbaching, 3 years ago

#2911: adding TSQLExpressionFormatter with boiler-plate code for scalar function or inline select

File size: 12.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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  public static class StringBuilderExtensions {
34    public static void AppendIndented(this StringBuilder strBuilder, int level, string text) {
35      strBuilder.Append(new String(' ', level * 2));
36      strBuilder.Append(text);
37    }
38    public static void AppendLineIndented(this StringBuilder strBuilder, int level, string text) {
39      strBuilder.Append(new String(' ', level * 2));
40      strBuilder.AppendLine(text);
41    }
42  }
43
44  [Item("TSQL String Formatter", "String formatter for string representations of symbolic data analysis expressions in TSQL syntax.")]
45  [StorableClass]
46  public sealed class TSQLExpressionFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
47    [StorableConstructor]
48    private TSQLExpressionFormatter(bool deserializing) : base(deserializing) { }
49    private TSQLExpressionFormatter(TSQLExpressionFormatter original, Cloner cloner) : base(original, cloner) { }
50    public TSQLExpressionFormatter()
51      : base() {
52      Name = ItemName;
53      Description = ItemDescription;
54    }
55    public override IDeepCloneable Clone(Cloner cloner) {
56      return new TSQLExpressionFormatter(this, cloner);
57    }
58
59    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
60      // skip root and start symbols
61      StringBuilder strBuilder = new StringBuilder();
62      GenerateHeader(strBuilder, symbolicExpressionTree);
63
64      //generate function body
65      FormatRecursively(1, symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0), strBuilder);
66
67      GenerateFooter(strBuilder);
68      return strBuilder.ToString();
69    }
70
71    private void GenerateHeader(StringBuilder strBuilder, ISymbolicExpressionTree symbolicExpressionTree) {
72      HashSet<string> floatVarNames = new HashSet<string>();
73      foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode || x is VariableConditionTreeNode)) {
74        floatVarNames.Add(((IVariableTreeNode)node).VariableName);
75      }
76      var sortedFloatIdentifiers = floatVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => VariableName2Identifier(n)).ToList();
77
78      HashSet<string> varcharVarNames = new HashSet<string>();
79      foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is BinaryFactorVariableTreeNode || x is FactorVariableTreeNode)) {
80        varcharVarNames.Add(((IVariableTreeNode)node).VariableName);
81      }
82      var sortedVarcharIdentifiers = varcharVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => VariableName2Identifier(n)).ToList();
83
84      //Generate comment and instructions
85      strBuilder.Append($"-- generated. created function can be used like 'SELECT dbo.REGRESSIONMODEL(");
86      strBuilder.Append(string.Join(", ", sortedVarcharIdentifiers));
87      if (varcharVarNames.Any() && floatVarNames.Any())
88        strBuilder.Append(",");
89      strBuilder.Append(string.Join(", ", sortedFloatIdentifiers));
90      strBuilder.AppendLine(")'");
91      strBuilder.AppendLine($"-- use the expression after the RETURN statement if you want to incorporate the model in a query without creating a function.");
92
93      //Generate function header
94      strBuilder.Append($"CREATE FUNCTION dbo.REGRESSIONMODEL(");
95      strBuilder.Append(string.Join(", ", sortedVarcharIdentifiers.Select(n => $"{n} NVARCHAR(max)")));
96      if (varcharVarNames.Any() && floatVarNames.Any())
97        strBuilder.Append(",");
98      strBuilder.Append(string.Join(", ", sortedFloatIdentifiers.Select(n => $"{n} FLOAT")));
99      strBuilder.AppendLine(")");
100
101      //start function body
102      strBuilder.AppendLine("RETURNS FLOAT");
103      strBuilder.AppendLine("BEGIN");
104
105      //add variable declaration for convenience
106      strBuilder.AppendLineIndented(1,$"-- added variable declaration for convenience");
107      foreach (var name in sortedVarcharIdentifiers)
108        strBuilder.AppendLineIndented(1, $"-- DECLARE {name} NVARCHAR(max) = ''");
109      foreach (var name in sortedFloatIdentifiers)
110        strBuilder.AppendLineIndented(1, $"-- DECLARE {name} FLOAT = 0.0");
111      strBuilder.AppendLineIndented(1, $"-- SELECT");
112      strBuilder.AppendLine("RETURN ");
113    }
114
115    private void FormatRecursively(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
116      // TODO: adapt to interpreter semantics. The HL interpreter also allows Boolean operations on reals
117      if (node.Subtrees.Any()) {
118        if (node.Symbol is Addition) {
119          FormatOperator(level, node, "+", strBuilder);
120        } else if (node.Symbol is And) {
121          FormatOperator(level, node, "AND", strBuilder);
122        } else if (node.Symbol is Average) {
123          throw new NotSupportedException($"Symbol {node.Symbol.GetType().Name} not yet supported.");
124        } else if (node.Symbol is Cosine) {
125          FormatFunction(level, node, "COS", strBuilder);
126        } else if (node.Symbol is Division) {
127          FormatDivision(level, node, strBuilder);
128        } else if (node.Symbol is Exponential) {
129          FormatFunction(level, node, "EXP", strBuilder);
130        } else if (node.Symbol is GreaterThan) {
131          FormatOperator(level, node, ">", strBuilder);
132        } else if (node.Symbol is IfThenElse) {
133          throw new NotSupportedException($"Symbol {node.Symbol.GetType().Name} not yet supported.");
134        } else if (node.Symbol is LessThan) {
135          FormatOperator(level, node, "<", strBuilder);
136        } else if (node.Symbol is Logarithm) {
137          FormatFunction(level, node, "LOG", strBuilder);
138        } else if (node.Symbol is Multiplication) {
139          FormatOperator(level, node, "*", strBuilder);
140        } else if (node.Symbol is Not) {
141          throw new NotSupportedException($"Symbol {node.Symbol.GetType().Name} not yet supported.");
142        } else if (node.Symbol is Or) {
143          FormatOperator(level, node, "OR", strBuilder);
144        } else if (node.Symbol is Xor) {
145          throw new NotSupportedException($"Symbol {node.Symbol.GetType().Name} not yet supported.");
146        } else if (node.Symbol is Sine) {
147          FormatFunction(level, node, "SIN", strBuilder);
148        } else if (node.Symbol is Subtraction) {
149          FormatSubtraction(level, node, strBuilder);
150        } else if (node.Symbol is Tangent) {
151          FormatFunction(level, node, "TAN", strBuilder);
152        } else if (node.Symbol is Square) {
153          FormatFunction(level, node, "SQUARE", strBuilder);
154        } else if (node.Symbol is SquareRoot) {
155          FormatFunction(level, node, "SQRT", strBuilder);
156        } else if (node.Symbol is Power) {
157          FormatFunction(level, node, "POWER", strBuilder);
158        } else if (node.Symbol is Root) {
159          FormatRoot(level, node, strBuilder);
160        } else {
161          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
162        }
163      } else {
164        if (node is VariableTreeNode) {
165          var varNode = node as VariableTreeNode;
166          strBuilder.AppendFormat("{0} * {1}", VariableName2Identifier(varNode.VariableName), varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));
167        } else if (node is ConstantTreeNode) {
168          var constNode = node as ConstantTreeNode;
169          strBuilder.Append(constNode.Value.ToString("g17", CultureInfo.InvariantCulture));
170        } else if (node.Symbol is FactorVariable) {
171          var factorNode = node as FactorVariableTreeNode;
172          FormatFactor(level, factorNode, strBuilder);
173        } else if (node.Symbol is BinaryFactorVariable) {
174          var binFactorNode = node as BinaryFactorVariableTreeNode;
175          throw new NotSupportedException($"Symbol {node.Symbol.GetType().Name} not yet supported.");
176        } else {
177          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
178        }
179      }
180    }
181
182    private string VariableName2Identifier(string variableName) {
183      return $"@{variableName.Replace(' ', '_')}";
184    }
185
186    private void GenerateFooter(StringBuilder strBuilder) {
187      strBuilder.AppendLine($"{Environment.NewLine}END");
188    }
189
190
191    private void FormatOperator(int level, ISymbolicExpressionTreeNode node, string symbol, StringBuilder strBuilder) {
192      strBuilder.Append("(");
193      foreach (var child in node.Subtrees) {
194        FormatRecursively(level, child, strBuilder);
195        if (child != node.Subtrees.Last())
196          strBuilder.Append(" " + symbol + " ");
197      }
198      strBuilder.Append(")");
199    }
200
201    private void FormatFunction(int level, ISymbolicExpressionTreeNode node, string function, StringBuilder strBuilder) {
202      strBuilder.Append(function + "(");
203      foreach (var child in node.Subtrees) {
204        FormatRecursively(level++, child, strBuilder);
205        if (child != node.Subtrees.Last())
206          strBuilder.Append( ", ");
207      }
208      strBuilder.Append(")");
209    }
210
211    private void FormatDivision(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
212      if (node.SubtreeCount == 1) {
213        strBuilder.Append("1.0 / ");
214        FormatRecursively(level, node.GetSubtree(0), strBuilder);
215      } else {
216        FormatRecursively(level, node.GetSubtree(0), strBuilder);
217        strBuilder.Append("/ (");
218        for (int i = 1; i < node.SubtreeCount; i++) {
219          if (i > 1) strBuilder.Append(" * ");
220          FormatRecursively(level, node.GetSubtree(i), strBuilder);
221        }
222        strBuilder.Append(")");
223      }
224    }
225
226    private void FormatSubtraction(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
227      if (node.SubtreeCount == 1) {
228        strBuilder.Append("-");
229        FormatRecursively(level, node.GetSubtree(0), strBuilder);
230        return;
231      }
232      //Default case: more than 1 child
233      FormatOperator(level, node, "-", strBuilder);
234    }
235
236    private void FormatRoot(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
237      strBuilder.AppendLine("POWER(");
238      FormatRecursively(level, node.GetSubtree(0), strBuilder);
239      strBuilder.AppendLineIndented(level, " , 1.0 / (");
240      FormatRecursively(level, node.GetSubtree(1), strBuilder);
241      strBuilder.AppendLineIndented(level, "))");
242    }
243
244    private void FormatFactor(int level, FactorVariableTreeNode node, StringBuilder strBuilder) {
245      strBuilder.AppendLine($"( ");
246      strBuilder.AppendLineIndented(level+1,$"CASE {VariableName2Identifier(node.VariableName)}");
247      foreach (var name in node.Symbol.GetVariableValues(node.VariableName)) {
248        strBuilder.AppendLineIndented(level + 2, $"WHEN '{name}' THEN {node.GetValue(name).ToString(CultureInfo.InvariantCulture)}");
249      }
250      strBuilder.AppendLineIndented(level+1, "ELSE NULL END");
251      strBuilder.AppendIndented(level, ")");
252    }
253
254  }
255}
Note: See TracBrowser for help on using the repository browser.