Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/InfixExpressionFormatter.cs @ 14347

Last change on this file since 14347 was 14347, checked in by gkronber, 8 years ago

#2677: extended infix parser and infix formatter to support functions with multiple arguments

File size: 5.7 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 Variable) {
113          var varNode = node as VariableTreeNode;
114          if (!varNode.Weight.IsAlmost(1.0)) {
115            strBuilder.Append("(");
116            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Weight);
117            strBuilder.Append("*");
118          }
119          if (varNode.VariableName.Contains("'")) {
120            strBuilder.AppendFormat("\"{0}\"", varNode.VariableName);
121          } else {
122            strBuilder.AppendFormat("'{0}'", varNode.VariableName);
123          }
124          if (!varNode.Weight.IsAlmost(1.0)) {
125            strBuilder.Append(")");
126          }
127        } else if (node.Symbol is Constant) {
128          var constNode = node as ConstantTreeNode;
129          if (constNode.Value >= 0.0)
130            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", constNode.Value);
131          else
132            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", constNode.Value);     // (-1)
133        }
134      }
135    }
136
137    private string GetToken(ISymbol symbol) {
138      var tok = InfixExpressionParser.knownSymbols.GetBySecond(symbol).SingleOrDefault();
139      if (tok == null)
140        throw new ArgumentException(string.Format("Unknown symbol {0} found.", symbol.Name));
141      return tok;
142    }
143  }
144}
Note: See TracBrowser for help on using the repository browser.