Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/InfixExpressionFormatter.cs @ 14536

Last change on this file since 14536 was 14312, checked in by bburlacu, 8 years ago

#1772: Merge trunk changes. Delete unnecessary files (sliding window).

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.Globalization;
24using System.Linq;
25using System.Text;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
32  /// <summary>
33  /// Formats mathematical expressions in infix form. E.g. x1 * (3.0 * x2 + x3)
34  /// </summary>
35  [StorableClass]
36  [Item("Infix Symbolic Expression Tree Formatter", "A string formatter that converts symbolic expression trees to infix expressions.")]
37
38  public sealed class InfixExpressionFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
39
40
41    [StorableConstructor]
42    private InfixExpressionFormatter(bool deserializing) : base(deserializing) { }
43    private InfixExpressionFormatter(InfixExpressionFormatter original, Cloner cloner) : base(original, cloner) { }
44    public InfixExpressionFormatter()
45      : base() {
46      Name = ItemName;
47      Description = ItemDescription;
48    }
49    public override IDeepCloneable Clone(Cloner cloner) {
50      return new InfixExpressionFormatter(this, cloner);
51    }
52
53    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
54      // skip root and start symbols
55      StringBuilder strBuilder = new StringBuilder();
56      FormatRecursively(symbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0), strBuilder);
57      return strBuilder.ToString();
58    }
59
60    private void FormatRecursively(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
61      if (node.SubtreeCount > 1) {
62        var token = GetToken(node.Symbol);
63        if (token == "+" || token == "-" || token == "OR" || token == "XOR") {
64          strBuilder.Append("(");
65          FormatRecursively(node.Subtrees.First(), strBuilder);
66
67          foreach (var subtree in node.Subtrees.Skip(1)) {
68            strBuilder.Append(" ").Append(token).Append(" ");
69            FormatRecursively(subtree, strBuilder);
70          }
71          strBuilder.Append(")");
72
73        } else if (token == "*" || token == "/" || token == "AND") {
74          strBuilder.Append("(");
75          FormatRecursively(node.Subtrees.First(), strBuilder);
76
77          foreach (var subtree in node.Subtrees.Skip(1)) {
78            strBuilder.Append(" ").Append(token).Append(" ");
79            FormatRecursively(subtree, strBuilder);
80          }
81          strBuilder.Append(")");
82        }
83      } else if (node.SubtreeCount == 1) {
84        var token = GetToken(node.Symbol);
85        if (token == "-" || token == "NOT") {
86          strBuilder.Append("(").Append(token).Append("(");
87          FormatRecursively(node.GetSubtree(0), strBuilder);
88          strBuilder.Append("))");
89        } else if (token == "/") {
90          strBuilder.Append("1/");
91          FormatRecursively(node.GetSubtree(0), strBuilder);
92        } else if (token == "+" || token == "*") {
93          FormatRecursively(node.GetSubtree(0), strBuilder);
94        } else {
95          // function
96          strBuilder.Append(token).Append("(");
97          FormatRecursively(node.GetSubtree(0), strBuilder);
98          strBuilder.Append(")");
99        }
100      } else {
101        // no subtrees
102        if (node.Symbol is Variable) {
103          var varNode = node as VariableTreeNode;
104          if (!varNode.Weight.IsAlmost(1.0)) {
105            strBuilder.Append("(");
106            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", varNode.Weight);
107            strBuilder.Append("*");
108          }
109          if (varNode.VariableName.Contains("'")) {
110            strBuilder.AppendFormat("\"{0}\"", varNode.VariableName);
111          } else {
112            strBuilder.AppendFormat("'{0}'", varNode.VariableName);
113          }
114          if (!varNode.Weight.IsAlmost(1.0)) {
115            strBuilder.Append(")");
116          }
117        } else if (node.Symbol is Constant) {
118          var constNode = node as ConstantTreeNode;
119          if (constNode.Value >= 0.0)
120            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", constNode.Value);
121          else
122            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", constNode.Value);     // (-1)
123        }
124      }
125    }
126
127    private string GetToken(ISymbol symbol) {
128      var tok = InfixExpressionParser.knownSymbols.GetBySecond(symbol).SingleOrDefault();
129      if (tok == null)
130        throw new ArgumentException(string.Format("Unknown symbol {0} found.", symbol.Name));
131      return tok;
132    }
133  }
134}
Note: See TracBrowser for help on using the repository browser.