Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/InfixExpressionFormatter.cs @ 15142

Last change on this file since 15142 was 15131, checked in by gkronber, 7 years ago

#2650: merged r14826 from trunk to stable. The only remaining conflict is DataTableControl and ScatterPlotControl which have been renamed within r14982 (-> tree conflict).

File size: 7.9 KB
Line 
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
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  /// <summary>
34  /// Formats mathematical expressions in infix form. E.g. x1 * (3.0 * x2 + x3)
35  /// </summary>
36  [StorableClass]
37  [Item("Infix Symbolic Expression Tree Formatter", "A string formatter that converts symbolic expression trees to infix expressions.")]
38
39  public sealed class InfixExpressionFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
40
41
42    [StorableConstructor]
43    private InfixExpressionFormatter(bool deserializing) : base(deserializing) { }
44    private InfixExpressionFormatter(InfixExpressionFormatter original, Cloner cloner) : base(original, cloner) { }
45    public InfixExpressionFormatter()
46      : base() {
47      Name = ItemName;
48      Description = ItemDescription;
49    }
50    public override IDeepCloneable Clone(Cloner cloner) {
51      return new InfixExpressionFormatter(this, cloner);
52    }
53
54    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
55      // skip root and start symbols
56      StringBuilder strBuilder = new StringBuilder();
57      FormatRecursively(symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0), strBuilder);
58      return strBuilder.ToString();
59    }
60
61    private void FormatRecursively(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
62      if (node.SubtreeCount > 1) {
63        var token = GetToken(node.Symbol);
64        if (token == "+" || token == "-" || token == "OR" || token == "XOR") {
65          strBuilder.Append("(");
66          FormatRecursively(node.Subtrees.First(), strBuilder);
67
68          foreach (var subtree in node.Subtrees.Skip(1)) {
69            strBuilder.Append(" ").Append(token).Append(" ");
70            FormatRecursively(subtree, strBuilder);
71          }
72          strBuilder.Append(")");
73
74        } else if (token == "*" || token == "/" || token == "AND") {
75          strBuilder.Append("(");
76          FormatRecursively(node.Subtrees.First(), strBuilder);
77
78          foreach (var subtree in node.Subtrees.Skip(1)) {
79            strBuilder.Append(" ").Append(token).Append(" ");
80            FormatRecursively(subtree, strBuilder);
81          }
82          strBuilder.Append(")");
83        } else {
84          // function with multiple arguments
85          strBuilder.Append(token).Append("(");
86          FormatRecursively(node.Subtrees.First(), strBuilder);
87          foreach (var subtree in node.Subtrees.Skip(1)) {
88            strBuilder.Append(", ");
89            FormatRecursively(subtree, strBuilder);
90          }
91          strBuilder.Append(")");
92        }
93      } else if (node.SubtreeCount == 1) {
94        var token = GetToken(node.Symbol);
95        if (token == "-" || token == "NOT") {
96          strBuilder.Append("(").Append(token).Append("(");
97          FormatRecursively(node.GetSubtree(0), strBuilder);
98          strBuilder.Append("))");
99        } else if (token == "/") {
100          strBuilder.Append("1/");
101          FormatRecursively(node.GetSubtree(0), strBuilder);
102        } else if (token == "+" || token == "*") {
103          FormatRecursively(node.GetSubtree(0), strBuilder);
104        } else {
105          // function with only one argument
106          strBuilder.Append(token).Append("(");
107          FormatRecursively(node.GetSubtree(0), strBuilder);
108          strBuilder.Append(")");
109        }
110      } else {
111        // no subtrees
112        if (node.Symbol is LaggedVariable) {
113          var varNode = node as LaggedVariableTreeNode;
114          if (!varNode.Weight.IsAlmost(1.0)) {
115            strBuilder.Append("(");
116            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Weight);
117            strBuilder.Append("*");
118          }
119          strBuilder.Append("LAG(");
120          if (varNode.VariableName.Contains("'")) {
121            strBuilder.AppendFormat("\"{0}\"", varNode.VariableName);
122          } else {
123            strBuilder.AppendFormat("'{0}'", varNode.VariableName);
124          }
125          strBuilder.Append(", ")
126            .AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Lag)
127            .Append(")");
128        } else if (node.Symbol is Variable) {
129          var varNode = node as VariableTreeNode;
130          if (!varNode.Weight.IsAlmost(1.0)) {
131            strBuilder.Append("(");
132            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Weight);
133            strBuilder.Append("*");
134          }
135          if (varNode.VariableName.Contains("'")) {
136            strBuilder.AppendFormat("\"{0}\"", varNode.VariableName);
137          } else {
138            strBuilder.AppendFormat("'{0}'", varNode.VariableName);
139          }
140          if (!varNode.Weight.IsAlmost(1.0)) {
141            strBuilder.Append(")");
142          }
143        } else if (node.Symbol is FactorVariable) {
144          var factorNode = node as FactorVariableTreeNode;
145          if (factorNode.VariableName.Contains("'")) {
146            strBuilder.AppendFormat("\"{0}\"", factorNode.VariableName);
147          } else {
148            strBuilder.AppendFormat("'{0}'", factorNode.VariableName);
149          }
150          strBuilder.AppendFormat("[{0}]",
151            string.Join(", ", factorNode.Weights.Select(w => w.ToString(CultureInfo.InvariantCulture))));
152        } else if (node.Symbol is BinaryFactorVariable) {
153          var factorNode = node as BinaryFactorVariableTreeNode;
154          if (!factorNode.Weight.IsAlmost(1.0)) {
155            strBuilder.Append("(");
156            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", factorNode.Weight);
157            strBuilder.Append("*");
158          }
159          if (factorNode.VariableName.Contains("'")) {
160            strBuilder.AppendFormat("\"{0}\"", factorNode.VariableName);
161          } else {
162            strBuilder.AppendFormat("'{0}'", factorNode.VariableName);
163          }
164          strBuilder.Append(" = ");
165          if (factorNode.VariableValue.Contains("'")) {
166            strBuilder.AppendFormat("\"{0}\"", factorNode.VariableValue);
167          } else {
168            strBuilder.AppendFormat("'{0}'", factorNode.VariableValue);
169          }
170
171          if (!factorNode.Weight.IsAlmost(1.0)) {
172            strBuilder.Append(")");
173          }
174
175        } else if (node.Symbol is Constant) {
176          var constNode = node as ConstantTreeNode;
177          if (constNode.Value >= 0.0)
178            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", constNode.Value);
179          else
180            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", constNode.Value); // (-1
181        }
182      }
183    }
184
185    private string GetToken(ISymbol symbol) {
186      var tok = InfixExpressionParser.knownSymbols.GetBySecond(symbol).SingleOrDefault();
187      if (tok == null)
188        throw new ArgumentException(string.Format("Unknown symbol {0} found.", symbol.Name));
189      return tok;
190    }
191  }
192}
Note: See TracBrowser for help on using the repository browser.