[14024] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[17180] | 3 | * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[14024] | 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;
|
---|
[17581] | 23 | using System.Collections.Generic;
|
---|
[14024] | 24 | using System.Globalization;
|
---|
| 25 | using System.Linq;
|
---|
| 26 | using System.Text;
|
---|
[17581] | 27 | using HEAL.Attic;
|
---|
[14024] | 28 | using HeuristicLab.Common;
|
---|
| 29 | using HeuristicLab.Core;
|
---|
| 30 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
[17685] | 31 | using Microsoft.SqlServer.Server;
|
---|
[14024] | 32 |
|
---|
| 33 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
|
---|
[17581] | 34 | public static class BaseInfixExpressionFormatter {
|
---|
| 35 | public static void FormatRecursively(ISymbolicExpressionTreeNode node, StringBuilder strBuilder,
|
---|
| 36 | NumberFormatInfo numberFormat, string formatString, List<KeyValuePair<string, double>> constants = null) {
|
---|
[14024] | 37 | if (node.SubtreeCount > 1) {
|
---|
| 38 | var token = GetToken(node.Symbol);
|
---|
[16359] | 39 | // operators
|
---|
| 40 | if (token == "+" || token == "-" || token == "OR" || token == "XOR" ||
|
---|
| 41 | token == "*" || token == "/" || token == "AND" ||
|
---|
| 42 | token == "^") {
|
---|
[14024] | 43 | strBuilder.Append("(");
|
---|
[17581] | 44 | FormatRecursively(node.Subtrees.First(), strBuilder, numberFormat, formatString, constants);
|
---|
[14024] | 45 |
|
---|
| 46 | foreach (var subtree in node.Subtrees.Skip(1)) {
|
---|
| 47 | strBuilder.Append(" ").Append(token).Append(" ");
|
---|
[17581] | 48 | FormatRecursively(subtree, strBuilder, numberFormat, formatString, constants);
|
---|
[14024] | 49 | }
|
---|
[17581] | 50 |
|
---|
[14024] | 51 | strBuilder.Append(")");
|
---|
[14347] | 52 | } else {
|
---|
| 53 | // function with multiple arguments
|
---|
| 54 | strBuilder.Append(token).Append("(");
|
---|
[17581] | 55 | FormatRecursively(node.Subtrees.First(), strBuilder, numberFormat, formatString, constants);
|
---|
[14347] | 56 | foreach (var subtree in node.Subtrees.Skip(1)) {
|
---|
| 57 | strBuilder.Append(", ");
|
---|
[17581] | 58 | FormatRecursively(subtree, strBuilder, numberFormat, formatString, constants);
|
---|
[14347] | 59 | }
|
---|
[17581] | 60 |
|
---|
[14347] | 61 | strBuilder.Append(")");
|
---|
[14024] | 62 | }
|
---|
| 63 | } else if (node.SubtreeCount == 1) {
|
---|
| 64 | var token = GetToken(node.Symbol);
|
---|
| 65 | if (token == "-" || token == "NOT") {
|
---|
| 66 | strBuilder.Append("(").Append(token).Append("(");
|
---|
[17581] | 67 | FormatRecursively(node.GetSubtree(0), strBuilder, numberFormat, formatString, constants);
|
---|
[14024] | 68 | strBuilder.Append("))");
|
---|
| 69 | } else if (token == "/") {
|
---|
| 70 | strBuilder.Append("1/");
|
---|
[17581] | 71 | FormatRecursively(node.GetSubtree(0), strBuilder, numberFormat, formatString, constants);
|
---|
[14024] | 72 | } else if (token == "+" || token == "*") {
|
---|
[17581] | 73 | FormatRecursively(node.GetSubtree(0), strBuilder, numberFormat, formatString, constants);
|
---|
[14024] | 74 | } else {
|
---|
[14347] | 75 | // function with only one argument
|
---|
[14024] | 76 | strBuilder.Append(token).Append("(");
|
---|
[17581] | 77 | FormatRecursively(node.GetSubtree(0), strBuilder, numberFormat, formatString, constants);
|
---|
[14024] | 78 | strBuilder.Append(")");
|
---|
| 79 | }
|
---|
| 80 | } else {
|
---|
| 81 | // no subtrees
|
---|
[14350] | 82 | if (node.Symbol is LaggedVariable) {
|
---|
| 83 | var varNode = node as LaggedVariableTreeNode;
|
---|
| 84 | if (!varNode.Weight.IsAlmost(1.0)) {
|
---|
| 85 | strBuilder.Append("(");
|
---|
[17685] | 86 | AppendConstant(strBuilder, constants, varNode.Weight, formatString, numberFormat);
|
---|
[14350] | 87 | strBuilder.Append("*");
|
---|
| 88 | }
|
---|
[17581] | 89 |
|
---|
[14350] | 90 | strBuilder.Append("LAG(");
|
---|
[17685] | 91 | AppendVariableName(strBuilder, varNode.VariableName);
|
---|
[14350] | 92 | strBuilder.Append(", ")
|
---|
[17581] | 93 | .AppendFormat(numberFormat, "{0}", varNode.Lag)
|
---|
| 94 | .Append(")");
|
---|
[17685] | 95 | if (!varNode.Weight.IsAlmost(1.0)) strBuilder.Append(")");
|
---|
[14350] | 96 | } else if (node.Symbol is Variable) {
|
---|
[14024] | 97 | var varNode = node as VariableTreeNode;
|
---|
| 98 | if (!varNode.Weight.IsAlmost(1.0)) {
|
---|
| 99 | strBuilder.Append("(");
|
---|
[17685] | 100 | AppendConstant(strBuilder, constants, varNode.Weight, formatString, numberFormat);
|
---|
[14024] | 101 | strBuilder.Append("*");
|
---|
| 102 | }
|
---|
[17581] | 103 |
|
---|
[17685] | 104 | AppendVariableName(strBuilder, varNode.VariableName);
|
---|
[17581] | 105 |
|
---|
| 106 | if (!varNode.Weight.IsAlmost(1.0)) strBuilder.Append(")");
|
---|
[14826] | 107 | } else if (node.Symbol is FactorVariable) {
|
---|
| 108 | var factorNode = node as FactorVariableTreeNode;
|
---|
[17685] | 109 | AppendVariableName(strBuilder, factorNode.VariableName);
|
---|
[17581] | 110 |
|
---|
[17685] | 111 | strBuilder.Append("[");
|
---|
| 112 | for (int i = 0; i < factorNode.Weights.Length; i++) {
|
---|
| 113 | if (i > 0) strBuilder.Append(", ");
|
---|
| 114 | AppendConstant(strBuilder, constants, factorNode.Weights[i], formatString, numberFormat);
|
---|
| 115 | }
|
---|
| 116 | strBuilder.Append("]");
|
---|
[14826] | 117 | } else if (node.Symbol is BinaryFactorVariable) {
|
---|
| 118 | var factorNode = node as BinaryFactorVariableTreeNode;
|
---|
| 119 | if (!factorNode.Weight.IsAlmost(1.0)) {
|
---|
| 120 | strBuilder.Append("(");
|
---|
[17685] | 121 | AppendConstant(strBuilder, constants, factorNode.Weight, formatString, numberFormat);
|
---|
[17581] | 122 |
|
---|
[14826] | 123 | strBuilder.Append("*");
|
---|
| 124 | }
|
---|
[17581] | 125 |
|
---|
[17685] | 126 | AppendVariableName(strBuilder, factorNode.VariableName);
|
---|
[14826] | 127 | strBuilder.Append(" = ");
|
---|
[17685] | 128 | AppendVariableName(strBuilder, factorNode.VariableValue);
|
---|
[14826] | 129 |
|
---|
[17581] | 130 | if (!factorNode.Weight.IsAlmost(1.0)) strBuilder.Append(")");
|
---|
[14024] | 131 | } else if (node.Symbol is Constant) {
|
---|
| 132 | var constNode = node as ConstantTreeNode;
|
---|
[17685] | 133 | if(constants==null && constNode.Value < 0) {
|
---|
| 134 | strBuilder.Append("(").Append(constNode.Value.ToString(formatString, numberFormat))
|
---|
| 135 | .Append(")"); // (-1
|
---|
[17581] | 136 | } else {
|
---|
[17685] | 137 | AppendConstant(strBuilder, constants, constNode.Value, formatString, numberFormat);
|
---|
[17581] | 138 | }
|
---|
[14024] | 139 | }
|
---|
| 140 | }
|
---|
| 141 | }
|
---|
| 142 |
|
---|
[17685] | 143 | private static void AppendConstant(StringBuilder strBuilder, List<KeyValuePair<string, double>> constants, double value, string formatString, NumberFormatInfo numberFormat) {
|
---|
| 144 | if (constants != null) {
|
---|
| 145 | string constantKey = $"c_{constants.Count}";
|
---|
| 146 | strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", constantKey);
|
---|
| 147 | constants.Add(new KeyValuePair<string, double>(constantKey, value));
|
---|
| 148 | } else {
|
---|
| 149 | strBuilder.Append(value.ToString(formatString, numberFormat));
|
---|
| 150 | }
|
---|
| 151 | }
|
---|
| 152 |
|
---|
| 153 | private static void AppendVariableName(StringBuilder strBuilder, string name) {
|
---|
| 154 | if (name.Contains("'"))
|
---|
| 155 | strBuilder.AppendFormat("\"{0}\"", name);
|
---|
| 156 | else
|
---|
| 157 | strBuilder.AppendFormat("'{0}'", name);
|
---|
| 158 | }
|
---|
| 159 |
|
---|
[16700] | 160 | private static string GetToken(ISymbol symbol) {
|
---|
[16359] | 161 | var tok = InfixExpressionParser.knownSymbols.GetBySecond(symbol).FirstOrDefault();
|
---|
[14024] | 162 | if (tok == null)
|
---|
| 163 | throw new ArgumentException(string.Format("Unknown symbol {0} found.", symbol.Name));
|
---|
| 164 | return tok;
|
---|
| 165 | }
|
---|
| 166 | }
|
---|
[17581] | 167 |
|
---|
| 168 | /// <summary>
|
---|
| 169 | /// Formats mathematical expressions in infix form. E.g. x1 * (3.0 * x2 + x3)
|
---|
| 170 | /// </summary>
|
---|
| 171 | [StorableType("6FE2C83D-A594-4ABF-B101-5AEAEA6D3E3D")]
|
---|
| 172 | [Item("Infix Symbolic Expression Tree Formatter",
|
---|
| 173 | "A string formatter that converts symbolic expression trees to infix expressions.")]
|
---|
| 174 | public sealed class InfixExpressionFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
|
---|
| 175 | [StorableConstructor]
|
---|
| 176 | private InfixExpressionFormatter(StorableConstructorFlag _) : base(_) { }
|
---|
| 177 |
|
---|
| 178 | private InfixExpressionFormatter(InfixExpressionFormatter original, Cloner cloner) : base(original, cloner) { }
|
---|
| 179 |
|
---|
| 180 | public InfixExpressionFormatter()
|
---|
| 181 | : base() {
|
---|
| 182 | Name = ItemName;
|
---|
| 183 | Description = ItemDescription;
|
---|
| 184 | }
|
---|
| 185 |
|
---|
| 186 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 187 | return new InfixExpressionFormatter(this, cloner);
|
---|
| 188 | }
|
---|
| 189 |
|
---|
| 190 | /// <summary>
|
---|
| 191 | /// Produces an infix expression for a given expression tree.
|
---|
| 192 | /// </summary>
|
---|
| 193 | /// <param name="symbolicExpressionTree">The tree representation of the expression.</param>
|
---|
| 194 | /// <param name="numberFormat">Number format that should be used for numeric parameters (e.g. NumberFormatInfo.InvariantInfo (default)).</param>
|
---|
| 195 | /// <param name="formatString">The format string for numeric parameters (e.g. \"G4\" to limit to 4 digits, default is \"G\")</param>
|
---|
| 196 | /// <returns>Infix expression</returns>
|
---|
| 197 | public string Format(ISymbolicExpressionTree symbolicExpressionTree, NumberFormatInfo numberFormat,
|
---|
| 198 | string formatString = "G") {
|
---|
| 199 | // skip root and start symbols
|
---|
| 200 | StringBuilder strBuilder = new StringBuilder();
|
---|
| 201 | BaseInfixExpressionFormatter.FormatRecursively(symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0),
|
---|
| 202 | strBuilder, numberFormat, formatString);
|
---|
| 203 | return strBuilder.ToString();
|
---|
| 204 | }
|
---|
| 205 |
|
---|
| 206 | public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
|
---|
| 207 | return Format(symbolicExpressionTree, NumberFormatInfo.InvariantInfo);
|
---|
| 208 | }
|
---|
| 209 | }
|
---|
| 210 |
|
---|
| 211 | [StorableType("54D917E8-134E-4066-9A60-2737C12D81DC")]
|
---|
| 212 | [Item("Infix String Formater", "Formatter for symbolic expressions, which produces an infix expression " +
|
---|
| 213 | "as well as a list of all coefficient values")]
|
---|
| 214 | public sealed class InfixExpressionStringFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
|
---|
| 215 | [StorableConstructor]
|
---|
| 216 | private InfixExpressionStringFormatter(StorableConstructorFlag _) : base(_) { }
|
---|
| 217 |
|
---|
| 218 | private InfixExpressionStringFormatter(InfixExpressionStringFormatter original, Cloner cloner) : base(original, cloner) { }
|
---|
| 219 |
|
---|
| 220 | public InfixExpressionStringFormatter() : base() {
|
---|
| 221 | Name = ItemName;
|
---|
| 222 | Description = ItemDescription;
|
---|
| 223 | }
|
---|
| 224 |
|
---|
| 225 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 226 | return new InfixExpressionStringFormatter(this, cloner);
|
---|
| 227 | }
|
---|
| 228 |
|
---|
| 229 | public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
|
---|
| 230 | StringBuilder strBuilder = new StringBuilder();
|
---|
| 231 | var constants = new List<KeyValuePair<string, double>>();
|
---|
| 232 | BaseInfixExpressionFormatter.FormatRecursively(symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0),
|
---|
| 233 | strBuilder, NumberFormatInfo.InvariantInfo, "G", constants);
|
---|
| 234 | strBuilder.Append($"{Environment.NewLine}{Environment.NewLine}");
|
---|
| 235 |
|
---|
| 236 | int maxDigits = GetDigits(constants.Count);
|
---|
| 237 | int padding = constants.Max(x => x.Value.ToString("F12", CultureInfo.InvariantCulture).Length);
|
---|
| 238 | foreach (var constant in constants) {
|
---|
| 239 | int digits = GetDigits(Int32.Parse(constant.Key.Substring(2)));
|
---|
| 240 | strBuilder.Append($"{constant.Key}{new String(' ', maxDigits - digits)} = " +
|
---|
| 241 | string.Format($"{{0,{padding}:F12}}", constant.Value, CultureInfo.InvariantCulture) +
|
---|
| 242 | Environment.NewLine);
|
---|
| 243 | }
|
---|
| 244 |
|
---|
| 245 | return strBuilder.ToString();
|
---|
| 246 | }
|
---|
| 247 |
|
---|
| 248 | private int GetDigits(int x) {
|
---|
| 249 | if (x == 0) return 1;
|
---|
| 250 | return (int)Math.Floor(Math.Log10(x) + 1);
|
---|
| 251 | }
|
---|
| 252 | }
|
---|
[14024] | 253 | }
|
---|