Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMATLABFormatter.cs @ 7653

Last change on this file since 7653 was 7653, checked in by gkronber, 12 years ago

#1801: fixed bug in MATLAB formatter for subtraction operators

File size: 12.9 KB
RevLine 
[5017]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5017]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.Text;
[5019]23using System.Linq;
[5017]24using HeuristicLab.Core;
25using HeuristicLab.Common;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27using HeuristicLab.Problems.DataAnalysis;
28using System.Collections.Generic;
29using System;
[5431]30using System.Globalization;
[5745]31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[5017]32
[5745]33namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[5017]34
[5745]35  [Item("MATLAB String Formatter", "String formatter for string representations of symbolic data analysis expressions in MATLAB syntax.")]
[5431]36  [StorableClass]
[5745]37  public sealed class SymbolicDataAnalysisExpressionMATLABFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
[5431]38    private int currentLag;
[5017]39
[5431]40    [StorableConstructor]
[5745]41    private SymbolicDataAnalysisExpressionMATLABFormatter(bool deserializing) : base(deserializing) { }
42    private SymbolicDataAnalysisExpressionMATLABFormatter(SymbolicDataAnalysisExpressionMATLABFormatter original, Cloner cloner) : base(original, cloner) { }
43    public SymbolicDataAnalysisExpressionMATLABFormatter()
[5019]44      : base() {
[5745]45      Name = ItemName;
46      Description = ItemDescription;
[5017]47    }
[5431]48    public override IDeepCloneable Clone(Cloner cloner) {
[5745]49      return new SymbolicDataAnalysisExpressionMATLABFormatter(this, cloner);
[5431]50    }
51    private int currentIndexNumber;
52    public string CurrentIndexVariable {
53      get {
54        return "i" + currentIndexNumber;
55      }
56    }
57    private void ReleaseIndexVariable() {
58      currentIndexNumber--;
59    }
[5017]60
[5431]61    private string AllocateIndexVariable() {
62      currentIndexNumber++;
63      return CurrentIndexVariable;
64    }
65
[5745]66    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
[5431]67      currentLag = 0;
68      currentIndexNumber = 0;
[7630]69
70      var stringBuilder = new StringBuilder();
71      stringBuilder.AppendLine("rows = ???");
72      stringBuilder.AppendLine(FormatOnlyExpression(symbolicExpressionTree.Root) + ";");
73      stringBuilder.AppendLine();
74      stringBuilder.AppendLine("function y = log_(x)");
75      stringBuilder.AppendLine("  if(x<=0) y = NaN;");
76      stringBuilder.AppendLine("  else     y = log(x);");
77      stringBuilder.AppendLine("  end");
78      stringBuilder.AppendLine("end");
79      stringBuilder.AppendLine();
80      stringBuilder.AppendLine("function y = fivePoint(f0, f1, f3, f4)");
81      stringBuilder.AppendLine("  y = (f0 + 2*f1 - 2*f3 - f4) / 8;");
82      stringBuilder.AppendLine("end");
83      return stringBuilder.ToString();
[5017]84    }
85
[7630]86    public string FormatOnlyExpression(ISymbolicExpressionTreeNode expressionNode)
87    {
88      var stringBuilder = new StringBuilder();
89      stringBuilder.AppendLine("  for " + CurrentIndexVariable + " = 1:1:rows");
90      stringBuilder.AppendLine("    estimated(" + CurrentIndexVariable + ") = " + FormatRecursively(expressionNode.GetSubtree(0)) + ";");
91      stringBuilder.AppendLine("  end;");
92      return stringBuilder.ToString();
93    }
94
[5745]95    private string FormatRecursively(ISymbolicExpressionTreeNode node) {
96      ISymbol symbol = node.Symbol;
[5017]97      StringBuilder stringBuilder = new StringBuilder();
98
99      if (symbol is ProgramRootSymbol) {
[7630]100        stringBuilder.AppendLine(FormatRecursively(node.GetSubtree(0)));
101      } else if (symbol is StartSymbol)
[5745]102        return FormatRecursively(node.GetSubtree(0));
[7630]103      else if (symbol is Addition) {
104        stringBuilder.Append("(");
[6803]105        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]106          if (i > 0) stringBuilder.Append("+");
[5745]107          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]108        }
[7630]109        stringBuilder.Append(")");
[5017]110      } else if (symbol is And) {
[5021]111        stringBuilder.Append("((");
[6803]112        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]113          if (i > 0) stringBuilder.Append("&");
114          stringBuilder.Append("((");
[5745]115          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]116          stringBuilder.Append(")>0)");
117        }
[7630]118        stringBuilder.Append(")-0.5)*2");
119        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]120      } else if (symbol is Average) {
121        stringBuilder.Append("(1/");
[6803]122        stringBuilder.Append(node.SubtreeCount);
[5017]123        stringBuilder.Append(")*(");
[6803]124        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]125          if (i > 0) stringBuilder.Append("+");
126          stringBuilder.Append("(");
[5745]127          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]128          stringBuilder.Append(")");
129        }
130        stringBuilder.Append(")");
131      } else if (symbol is Constant) {
132        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
[5431]133        stringBuilder.Append(constantTreeNode.Value.ToString(CultureInfo.InvariantCulture));
[5017]134      } else if (symbol is Cosine) {
135        stringBuilder.Append("cos(");
[5745]136        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]137        stringBuilder.Append(")");
138      } else if (symbol is Division) {
[6803]139        if (node.SubtreeCount == 1) {
[5017]140          stringBuilder.Append("1/");
[5745]141          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]142        } else {
[5745]143          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]144          stringBuilder.Append("/(");
[6803]145          for (int i = 1; i < node.SubtreeCount; i++) {
[5017]146            if (i > 1) stringBuilder.Append("*");
[5745]147            stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]148          }
149          stringBuilder.Append(")");
150        }
151      } else if (symbol is Exponential) {
152        stringBuilder.Append("exp(");
[5745]153        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]154        stringBuilder.Append(")");
155      } else if (symbol is GreaterThan) {
[5021]156        stringBuilder.Append("((");
[5745]157        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]158        stringBuilder.Append(">");
[5745]159        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[7630]160        stringBuilder.Append(")-0.5)*2");
161        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]162      } else if (symbol is IfThenElse) {
163        stringBuilder.Append("(");
[5745]164        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]165        stringBuilder.Append(">0)*");
[5745]166        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[5017]167        stringBuilder.Append("+");
168        stringBuilder.Append("(");
[5745]169        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5021]170        stringBuilder.Append("<=0)*");
[5745]171        stringBuilder.Append(FormatRecursively(node.GetSubtree(2)));
[5017]172      } else if (symbol is LaggedVariable) {
[5431]173        // this if must be checked before if(symbol is LaggedVariable)
[5017]174        LaggedVariableTreeNode laggedVariableTreeNode = node as LaggedVariableTreeNode;
[5431]175        stringBuilder.Append(laggedVariableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
[5017]176        stringBuilder.Append("*");
[7630]177        stringBuilder.Append(laggedVariableTreeNode.VariableName +
178                             LagToString(currentLag + laggedVariableTreeNode.Lag));
[5017]179      } else if (symbol is LessThan) {
[5021]180        stringBuilder.Append("((");
[5745]181        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]182        stringBuilder.Append("<");
[5745]183        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[7630]184        stringBuilder.Append(")-0.5)*2");
185        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]186      } else if (symbol is Logarithm) {
[5022]187        stringBuilder.Append("log_(");
[5745]188        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]189        stringBuilder.Append(")");
190      } else if (symbol is Multiplication) {
[6803]191        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]192          if (i > 0) stringBuilder.Append("*");
[5745]193          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]194        }
195      } else if (symbol is Not) {
[5745]196        stringBuilder.Append("~(");
197        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
198        stringBuilder.Append(" > 0 )");
[5017]199      } else if (symbol is Or) {
[5021]200        stringBuilder.Append("((");
[6803]201        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]202          if (i > 0) stringBuilder.Append("|");
203          stringBuilder.Append("((");
[5745]204          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]205          stringBuilder.Append(")>0)");
206        }
[7630]207        stringBuilder.Append(")-0.5)*2");
208        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]209      } else if (symbol is Sine) {
210        stringBuilder.Append("sin(");
[5745]211        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]212        stringBuilder.Append(")");
213      } else if (symbol is Subtraction) {
[7653]214        stringBuilder.Append("(");
[6803]215        if (node.SubtreeCount == 1) {
[7653]216          stringBuilder.Append("-");
[5745]217          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]218        } else {
[5745]219          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[6803]220          for (int i = 1; i < node.SubtreeCount; i++) {
[5017]221            stringBuilder.Append("-");
[5745]222            stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]223          }
224        }
[7653]225        stringBuilder.Append(")");
[5017]226      } else if (symbol is Tangent) {
227        stringBuilder.Append("tan(");
[5745]228        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]229        stringBuilder.Append(")");
[5745]230      } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Variable) {
[5017]231        VariableTreeNode variableTreeNode = node as VariableTreeNode;
[5431]232        stringBuilder.Append(variableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
[5017]233        stringBuilder.Append("*");
[5431]234        stringBuilder.Append(variableTreeNode.VariableName + LagToString(currentLag));
235      } else if (symbol is Power) {
236        stringBuilder.Append("(");
[5745]237        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]238        stringBuilder.Append(")^round(");
[5745]239        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[5431]240        stringBuilder.Append(")");
241      } else if (symbol is Root) {
242        stringBuilder.Append("(");
[5745]243        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]244        stringBuilder.Append(")^(1 / round(");
[5745]245        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[5431]246        stringBuilder.Append("))");
247      } else if (symbol is Derivative) {
248        stringBuilder.Append("fivePoint(");
249        // f0
[5745]250        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]251        stringBuilder.Append(", ");
252        // f1
253        currentLag--;
[5745]254        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]255        stringBuilder.Append(", ");
256        // f3
257        currentLag -= 2;
[5745]258        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]259        stringBuilder.Append(", ");
260        currentLag--;
261        // f4
[5745]262        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]263        stringBuilder.Append(")");
264        currentLag += 4;
265      } else if (symbol is Integral) {
266        var laggedNode = node as LaggedTreeNode;
267        string prevCounterVariable = CurrentIndexVariable;
268        string counterVariable = AllocateIndexVariable();
[7630]269        stringBuilder.AppendLine(" sum (map(@(" + counterVariable + ") " + FormatRecursively(node.GetSubtree(0)) +
270                                 ", (" + prevCounterVariable + "+" + laggedNode.Lag + "):" + prevCounterVariable +
271                                 "))");
[5431]272        ReleaseIndexVariable();
273      } else if (symbol is TimeLag) {
274        var laggedNode = node as LaggedTreeNode;
275        currentLag += laggedNode.Lag;
[5745]276        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]277        currentLag -= laggedNode.Lag;
[5019]278      } else {
[5017]279        stringBuilder.Append("ERROR");
280      }
281      return stringBuilder.ToString();
282    }
283
[5431]284
[7630]285    private string LagToString(int lag)
286    {
[5431]287      if (lag < 0) {
288        return "(" + CurrentIndexVariable + "" + lag + ")";
289      } else if (lag > 0) {
290        return "(" + CurrentIndexVariable + "+" + lag + ")";
291      } else return "(" + CurrentIndexVariable + ")";
[5017]292    }
[5431]293
[5017]294  }
295}
Note: See TracBrowser for help on using the repository browser.