[15877] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[16565] | 3 | * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[15877] | 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 HeuristicLab.Common;
|
---|
| 28 | using HeuristicLab.Core;
|
---|
| 29 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
[16565] | 30 | using HEAL.Attic;
|
---|
[15877] | 31 |
|
---|
| 32 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
|
---|
[15881] | 33 | internal static class StringBuilderExtensions {
|
---|
| 34 | internal static void AppendIndented(this StringBuilder strBuilder, int level, string text) {
|
---|
| 35 | strBuilder.Append(new string(' ', level * 2));
|
---|
[15877] | 36 | strBuilder.Append(text);
|
---|
| 37 | }
|
---|
[15881] | 38 | internal static void AppendLineIndented(this StringBuilder strBuilder, int level, string text) {
|
---|
| 39 | strBuilder.Append(new string(' ', level * 2));
|
---|
[15877] | 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.")]
|
---|
[16565] | 45 | [StorableType("549808A5-A062-4972-9DDB-E4B5CD392470")]
|
---|
[15877] | 46 | public sealed class TSQLExpressionFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
|
---|
| 47 | [StorableConstructor]
|
---|
[16565] | 48 | private TSQLExpressionFormatter(StorableConstructorFlag _) : base(_) { }
|
---|
[15877] | 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
|
---|
[15900] | 85 | strBuilder.Append("-- generated. created function can be used like 'SELECT dbo.REGRESSIONMODEL(");
|
---|
[15877] | 86 | strBuilder.Append(string.Join(", ", sortedVarcharIdentifiers));
|
---|
| 87 | if (varcharVarNames.Any() && floatVarNames.Any())
|
---|
| 88 | strBuilder.Append(",");
|
---|
| 89 | strBuilder.Append(string.Join(", ", sortedFloatIdentifiers));
|
---|
| 90 | strBuilder.AppendLine(")'");
|
---|
[15900] | 91 | strBuilder.AppendLine("-- use the expression after the RETURN statement if you want to incorporate the model in a query without creating a function.");
|
---|
[15877] | 92 |
|
---|
| 93 | //Generate function header
|
---|
[15900] | 94 | strBuilder.Append("CREATE FUNCTION dbo.REGRESSIONMODEL(");
|
---|
[15901] | 95 | strBuilder.Append(string.Join(", ", sortedVarcharIdentifiers.Select(n => string.Format("{0} NVARCHAR(max)",n))));
|
---|
[15877] | 96 | if (varcharVarNames.Any() && floatVarNames.Any())
|
---|
| 97 | strBuilder.Append(",");
|
---|
[15901] | 98 | strBuilder.Append(string.Join(", ", sortedFloatIdentifiers.Select(n => string.Format("{0} FLOAT",n))));
|
---|
[15877] | 99 | strBuilder.AppendLine(")");
|
---|
| 100 |
|
---|
| 101 | //start function body
|
---|
| 102 | strBuilder.AppendLine("RETURNS FLOAT");
|
---|
| 103 | strBuilder.AppendLine("BEGIN");
|
---|
| 104 |
|
---|
| 105 | //add variable declaration for convenience
|
---|
[15900] | 106 | strBuilder.AppendLineIndented(1, "-- added variable declaration for convenience");
|
---|
[15877] | 107 | foreach (var name in sortedVarcharIdentifiers)
|
---|
[15901] | 108 | strBuilder.AppendLineIndented(1, string.Format("-- DECLARE {0} NVARCHAR(max) = ''", name));
|
---|
[15877] | 109 | foreach (var name in sortedFloatIdentifiers)
|
---|
[15901] | 110 | strBuilder.AppendLineIndented(1, string.Format("-- DECLARE {0} FLOAT = 0.0", name));
|
---|
[15900] | 111 | strBuilder.AppendLineIndented(1, "-- SELECT");
|
---|
[15877] | 112 | strBuilder.AppendLine("RETURN ");
|
---|
| 113 | }
|
---|
| 114 |
|
---|
| 115 | private void FormatRecursively(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
| 116 | if (node.Subtrees.Any()) {
|
---|
| 117 | if (node.Symbol is Addition) {
|
---|
| 118 | FormatOperator(level, node, "+", strBuilder);
|
---|
| 119 | } else if (node.Symbol is And) {
|
---|
| 120 | FormatOperator(level, node, "AND", strBuilder);
|
---|
| 121 | } else if (node.Symbol is Average) {
|
---|
[15881] | 122 | FormatAverage(level, node, strBuilder);
|
---|
[15877] | 123 | } else if (node.Symbol is Cosine) {
|
---|
| 124 | FormatFunction(level, node, "COS", strBuilder);
|
---|
| 125 | } else if (node.Symbol is Division) {
|
---|
| 126 | FormatDivision(level, node, strBuilder);
|
---|
| 127 | } else if (node.Symbol is Exponential) {
|
---|
| 128 | FormatFunction(level, node, "EXP", strBuilder);
|
---|
| 129 | } else if (node.Symbol is GreaterThan) {
|
---|
| 130 | FormatOperator(level, node, ">", strBuilder);
|
---|
| 131 | } else if (node.Symbol is IfThenElse) {
|
---|
[15881] | 132 | FormatIfThenElse(level, node, strBuilder);
|
---|
[15877] | 133 | } else if (node.Symbol is LessThan) {
|
---|
| 134 | FormatOperator(level, node, "<", strBuilder);
|
---|
| 135 | } else if (node.Symbol is Logarithm) {
|
---|
| 136 | FormatFunction(level, node, "LOG", strBuilder);
|
---|
| 137 | } else if (node.Symbol is Multiplication) {
|
---|
| 138 | FormatOperator(level, node, "*", strBuilder);
|
---|
| 139 | } else if (node.Symbol is Not) {
|
---|
[15881] | 140 | FormatOperator(level, node, "NOT LIKE", strBuilder);
|
---|
[15877] | 141 | } else if (node.Symbol is Or) {
|
---|
| 142 | FormatOperator(level, node, "OR", strBuilder);
|
---|
| 143 | } else if (node.Symbol is Xor) {
|
---|
[15901] | 144 | throw new NotSupportedException(string.Format("Symbol {0} not yet supported.", node.Symbol.GetType().Name));
|
---|
[15877] | 145 | } else if (node.Symbol is Sine) {
|
---|
| 146 | FormatFunction(level, node, "SIN", strBuilder);
|
---|
| 147 | } else if (node.Symbol is Subtraction) {
|
---|
| 148 | FormatSubtraction(level, node, strBuilder);
|
---|
| 149 | } else if (node.Symbol is Tangent) {
|
---|
| 150 | FormatFunction(level, node, "TAN", strBuilder);
|
---|
| 151 | } else if (node.Symbol is Square) {
|
---|
| 152 | FormatFunction(level, node, "SQUARE", strBuilder);
|
---|
| 153 | } else if (node.Symbol is SquareRoot) {
|
---|
| 154 | FormatFunction(level, node, "SQRT", strBuilder);
|
---|
| 155 | } else if (node.Symbol is Power) {
|
---|
| 156 | FormatFunction(level, node, "POWER", strBuilder);
|
---|
| 157 | } else if (node.Symbol is Root) {
|
---|
| 158 | FormatRoot(level, node, strBuilder);
|
---|
| 159 | } else {
|
---|
[15881] | 160 | throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for TSQL symbolic expression tree formatter.");
|
---|
[15877] | 161 | }
|
---|
| 162 | } else {
|
---|
| 163 | if (node is VariableTreeNode) {
|
---|
| 164 | var varNode = node as VariableTreeNode;
|
---|
| 165 | strBuilder.AppendFormat("{0} * {1}", VariableName2Identifier(varNode.VariableName), varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));
|
---|
| 166 | } else if (node is ConstantTreeNode) {
|
---|
| 167 | var constNode = node as ConstantTreeNode;
|
---|
| 168 | strBuilder.Append(constNode.Value.ToString("g17", CultureInfo.InvariantCulture));
|
---|
| 169 | } else if (node.Symbol is FactorVariable) {
|
---|
| 170 | var factorNode = node as FactorVariableTreeNode;
|
---|
| 171 | FormatFactor(level, factorNode, strBuilder);
|
---|
| 172 | } else if (node.Symbol is BinaryFactorVariable) {
|
---|
| 173 | var binFactorNode = node as BinaryFactorVariableTreeNode;
|
---|
[15901] | 174 | throw new NotSupportedException(string.Format("Symbol {0} not yet supported.", node.Symbol.GetType().Name));
|
---|
[15877] | 175 | } else {
|
---|
[15881] | 176 | throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for TSQL symbolic expression tree formatter.");
|
---|
[15877] | 177 | }
|
---|
| 178 | }
|
---|
| 179 | }
|
---|
| 180 |
|
---|
[15881] | 181 | private void FormatIfThenElse(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
| 182 | strBuilder.Append("CASE ISNULL((SELECT 1 WHERE");
|
---|
| 183 | FormatRecursively(level,node.GetSubtree(0), strBuilder);
|
---|
| 184 | strBuilder.AppendLine("),0)");
|
---|
| 185 | strBuilder.AppendIndented(level,"WHEN 1 THEN ");
|
---|
| 186 | FormatRecursively(level, node.GetSubtree(1), strBuilder);
|
---|
| 187 | strBuilder.AppendLine();
|
---|
| 188 | strBuilder.AppendIndented(level, "WHEN 0 THEN ");
|
---|
| 189 | FormatRecursively(level, node.GetSubtree(2), strBuilder);
|
---|
| 190 | strBuilder.AppendLine();
|
---|
| 191 | strBuilder.AppendIndented(level, "END");
|
---|
| 192 | }
|
---|
| 193 |
|
---|
| 194 | private void FormatAverage(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
| 195 | strBuilder.Append("(");
|
---|
| 196 | foreach (var child in node.Subtrees) {
|
---|
| 197 | FormatRecursively(level, child, strBuilder);
|
---|
| 198 | if (child != node.Subtrees.Last())
|
---|
| 199 | strBuilder.Append(" + ");
|
---|
| 200 | }
|
---|
[15900] | 201 | strBuilder.AppendFormat(") / {0}", node.Subtrees.Count());
|
---|
[15881] | 202 | }
|
---|
| 203 |
|
---|
[15877] | 204 | private string VariableName2Identifier(string variableName) {
|
---|
[15900] | 205 | return "@"+variableName.Replace(' ', '_');
|
---|
[15877] | 206 | }
|
---|
| 207 |
|
---|
| 208 | private void GenerateFooter(StringBuilder strBuilder) {
|
---|
[15900] | 209 | strBuilder.Append(Environment.NewLine);
|
---|
| 210 | strBuilder.AppendLine("END");
|
---|
[15877] | 211 | }
|
---|
| 212 |
|
---|
| 213 |
|
---|
| 214 | private void FormatOperator(int level, ISymbolicExpressionTreeNode node, string symbol, StringBuilder strBuilder) {
|
---|
| 215 | strBuilder.Append("(");
|
---|
| 216 | foreach (var child in node.Subtrees) {
|
---|
| 217 | FormatRecursively(level, child, strBuilder);
|
---|
| 218 | if (child != node.Subtrees.Last())
|
---|
| 219 | strBuilder.Append(" " + symbol + " ");
|
---|
| 220 | }
|
---|
| 221 | strBuilder.Append(")");
|
---|
| 222 | }
|
---|
| 223 |
|
---|
| 224 | private void FormatFunction(int level, ISymbolicExpressionTreeNode node, string function, StringBuilder strBuilder) {
|
---|
| 225 | strBuilder.Append(function + "(");
|
---|
| 226 | foreach (var child in node.Subtrees) {
|
---|
| 227 | FormatRecursively(level++, child, strBuilder);
|
---|
| 228 | if (child != node.Subtrees.Last())
|
---|
[15881] | 229 | strBuilder.Append(", ");
|
---|
[15877] | 230 | }
|
---|
| 231 | strBuilder.Append(")");
|
---|
| 232 | }
|
---|
| 233 |
|
---|
| 234 | private void FormatDivision(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
| 235 | if (node.SubtreeCount == 1) {
|
---|
| 236 | strBuilder.Append("1.0 / ");
|
---|
| 237 | FormatRecursively(level, node.GetSubtree(0), strBuilder);
|
---|
| 238 | } else {
|
---|
| 239 | FormatRecursively(level, node.GetSubtree(0), strBuilder);
|
---|
| 240 | strBuilder.Append("/ (");
|
---|
| 241 | for (int i = 1; i < node.SubtreeCount; i++) {
|
---|
| 242 | if (i > 1) strBuilder.Append(" * ");
|
---|
| 243 | FormatRecursively(level, node.GetSubtree(i), strBuilder);
|
---|
| 244 | }
|
---|
| 245 | strBuilder.Append(")");
|
---|
| 246 | }
|
---|
| 247 | }
|
---|
| 248 |
|
---|
| 249 | private void FormatSubtraction(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
| 250 | if (node.SubtreeCount == 1) {
|
---|
| 251 | strBuilder.Append("-");
|
---|
| 252 | FormatRecursively(level, node.GetSubtree(0), strBuilder);
|
---|
| 253 | return;
|
---|
| 254 | }
|
---|
| 255 | //Default case: more than 1 child
|
---|
| 256 | FormatOperator(level, node, "-", strBuilder);
|
---|
| 257 | }
|
---|
| 258 |
|
---|
| 259 | private void FormatRoot(int level, ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
|
---|
| 260 | strBuilder.AppendLine("POWER(");
|
---|
| 261 | FormatRecursively(level, node.GetSubtree(0), strBuilder);
|
---|
| 262 | strBuilder.AppendLineIndented(level, " , 1.0 / (");
|
---|
| 263 | FormatRecursively(level, node.GetSubtree(1), strBuilder);
|
---|
| 264 | strBuilder.AppendLineIndented(level, "))");
|
---|
| 265 | }
|
---|
| 266 |
|
---|
| 267 | private void FormatFactor(int level, FactorVariableTreeNode node, StringBuilder strBuilder) {
|
---|
[15900] | 268 | strBuilder.AppendLine("( ");
|
---|
[15901] | 269 | strBuilder.AppendLineIndented(level + 1, string.Format("CASE {0}", VariableName2Identifier(node.VariableName)));
|
---|
[15877] | 270 | foreach (var name in node.Symbol.GetVariableValues(node.VariableName)) {
|
---|
[15901] | 271 | strBuilder.AppendLineIndented(level + 2, string.Format("WHEN '{0}' THEN {1}", name, node.GetValue(name).ToString(CultureInfo.InvariantCulture)));
|
---|
[15877] | 272 | }
|
---|
[15881] | 273 | strBuilder.AppendLineIndented(level + 1, "ELSE NULL END");
|
---|
[15877] | 274 | strBuilder.AppendIndented(level, ")");
|
---|
| 275 | }
|
---|
| 276 |
|
---|
| 277 | }
|
---|
| 278 | }
|
---|