Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2627: added first implementation of nonlinear regression algorithm + formatter and parser for infix expressions

File size: 5.3 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 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        }
84      } else if (node.SubtreeCount == 1) {
85        var token = GetToken(node.Symbol);
86        if (token == "-" || token == "NOT") {
87          strBuilder.Append("(").Append(token).Append("(");
88          FormatRecursively(node.GetSubtree(0), strBuilder);
89          strBuilder.Append("))");
90        } else if (token == "/") {
91          strBuilder.Append("1/");
92          FormatRecursively(node.GetSubtree(0), strBuilder);
93        } else if (token == "+" || token == "*") {
94          FormatRecursively(node.GetSubtree(0), strBuilder);
95        } else {
96          // function
97          strBuilder.Append(token).Append("(");
98          FormatRecursively(node.GetSubtree(0), strBuilder);
99          strBuilder.Append(")");
100        }
101      } else {
102        // no subtrees
103        if (node.Symbol is Variable) {
104          var varNode = node as VariableTreeNode;
105          if (!varNode.Weight.IsAlmost(1.0)) {
106            strBuilder.Append("(");
107            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Weight);
108            strBuilder.Append("*");
109          }
110          if (varNode.VariableName.Contains("'")) {
111            strBuilder.AppendFormat("\"{0}\"", varNode.VariableName);
112          } else {
113            strBuilder.AppendFormat("'{0}'", varNode.VariableName);
114          }
115          if (!varNode.Weight.IsAlmost(1.0)) {
116            strBuilder.Append(")");
117          }
118        } else if (node.Symbol is Constant) {
119          var constNode = node as ConstantTreeNode;
120          if (constNode.Value >= 0.0)
121            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", constNode.Value);
122          else
123            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", constNode.Value);     // (-1)
124        }
125      }
126    }
127
128    private string GetToken(ISymbol symbol) {
129      var tok = InfixExpressionParser.knownSymbols.GetBySecond(symbol).SingleOrDefault();
130      if (tok == null)
131        throw new ArgumentException(string.Format("Unknown symbol {0} found.", symbol.Name));
132      return tok;
133    }
134  }
135}
Note: See TracBrowser for help on using the repository browser.