Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.3/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/Formatters/SymbolicExpressionTreeMATLABFormatter.cs @ 13797

Last change on this file since 13797 was 5433, checked in by swinkler, 14 years ago

Fixed bugs in MATLAB formatter. (#1314)

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