Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/Formatters/SymbolicExpressionTreeMATLABFormatter.cs @ 5431

Last change on this file since 5431 was 5431, checked in by gkronber, 13 years ago

#1314 Merged MATLAB formatter from branch into trunk and implemented additional symbols related to dynamic modeling.

File size: 12.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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();
87        stringBuilder.AppendLine("  for "+CurrentIndexVariable+" = size(Data,1):-1:1");
88        stringBuilder.AppendLine("    Target_estimated("+CurrentIndexVariable+") = " + FormatRecursively(node.SubTrees[0]) + ";");
89        stringBuilder.AppendLine();
90        stringBuilder.AppendLine("function y = log_(x)");
91        stringBuilder.AppendLine("  if(x<=0) y = NaN;");
92        stringBuilder.AppendLine("  else     y = log(x);");
93        stringBuilder.AppendLine(
94@"
95function y = fivePoint(f0, f1, f3, f4)
96  y = (f0 + 2*f1 - 2*f3 - f4) / 8");
97        return stringBuilder.ToString();
98      }
99
100      if (symbol is StartSymbol)
101        return FormatRecursively(node.SubTrees[0]);
102
103      stringBuilder.Append("(");
104
105      if (symbol is Addition) {
106        for (int i = 0; i < node.SubTrees.Count; i++) {
107          if (i > 0) stringBuilder.Append("+");
108          stringBuilder.Append(FormatRecursively(node.SubTrees[i]));
109        }
110      } else if (symbol is And) {
111        stringBuilder.Append("((");
112        for (int i = 0; i < node.SubTrees.Count; i++) {
113          if (i > 0) stringBuilder.Append("&");
114          stringBuilder.Append("((");
115          stringBuilder.Append(FormatRecursively(node.SubTrees[i]));
116          stringBuilder.Append(")>0)");
117        }
118        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.
119      } else if (symbol is Average) {
120        stringBuilder.Append("(1/");
121        stringBuilder.Append(node.SubTrees.Count);
122        stringBuilder.Append(")*(");
123        for (int i = 0; i < node.SubTrees.Count; i++) {
124          if (i > 0) stringBuilder.Append("+");
125          stringBuilder.Append("(");
126          stringBuilder.Append(FormatRecursively(node.SubTrees[i]));
127          stringBuilder.Append(")");
128        }
129        stringBuilder.Append(")");
130      } else if (symbol is Constant) {
131        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
132        stringBuilder.Append(constantTreeNode.Value.ToString(CultureInfo.InvariantCulture));
133      } else if (symbol is Cosine) {
134        stringBuilder.Append("cos(");
135        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
136        stringBuilder.Append(")");
137      } else if (symbol is Division) {
138        if (node.SubTrees.Count == 1) {
139          stringBuilder.Append("1/");
140          stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
141        } else {
142          stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
143          stringBuilder.Append("/(");
144          for (int i = 1; i < node.SubTrees.Count; i++) {
145            if (i > 1) stringBuilder.Append("*");
146            stringBuilder.Append(FormatRecursively(node.SubTrees[i]));
147          }
148          stringBuilder.Append(")");
149        }
150      } else if (symbol is Exponential) {
151        stringBuilder.Append("exp(");
152        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
153        stringBuilder.Append(")");
154      } else if (symbol is GreaterThan) {
155        stringBuilder.Append("((");
156        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
157        stringBuilder.Append(">");
158        stringBuilder.Append(FormatRecursively(node.SubTrees[1]));
159        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.
160      } else if (symbol is IfThenElse) {
161        stringBuilder.Append("(");
162        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
163        stringBuilder.Append(">0)*");
164        stringBuilder.Append(FormatRecursively(node.SubTrees[1]));
165        stringBuilder.Append("+");
166        stringBuilder.Append("(");
167        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
168        stringBuilder.Append("<=0)*");
169        stringBuilder.Append(FormatRecursively(node.SubTrees[2]));
170      } else if (symbol is LaggedVariable) {
171        // this if must be checked before if(symbol is LaggedVariable)
172        LaggedVariableTreeNode laggedVariableTreeNode = node as LaggedVariableTreeNode;
173        stringBuilder.Append(laggedVariableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
174        stringBuilder.Append("*");
175        stringBuilder.Append(laggedVariableTreeNode.VariableName + LagToString(currentLag + laggedVariableTreeNode.Lag));
176      } else if (symbol is LessThan) {
177        stringBuilder.Append("((");
178        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
179        stringBuilder.Append("<");
180        stringBuilder.Append(FormatRecursively(node.SubTrees[1]));
181        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.
182      } else if (symbol is Logarithm) {
183        stringBuilder.Append("log_(");
184        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
185        stringBuilder.Append(")");
186      } else if (symbol is Multiplication) {
187        for (int i = 0; i < node.SubTrees.Count; i++) {
188          if (i > 0) stringBuilder.Append("*");
189          stringBuilder.Append(FormatRecursively(node.SubTrees[i]));
190        }
191      } else if (symbol is Not) {
192        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
193        stringBuilder.Append("*-1");
194      } else if (symbol is Or) {
195        stringBuilder.Append("((");
196        for (int i = 0; i < node.SubTrees.Count; i++) {
197          if (i > 0) stringBuilder.Append("|");
198          stringBuilder.Append("((");
199          stringBuilder.Append(FormatRecursively(node.SubTrees[i]));
200          stringBuilder.Append(")>0)");
201        }
202        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.
203      } else if (symbol is Sine) {
204        stringBuilder.Append("sin(");
205        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
206        stringBuilder.Append(")");
207      } else if (symbol is Subtraction) {
208        if (node.SubTrees.Count == 1) {
209          stringBuilder.Append("-1*");
210          stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
211        } else {
212          stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
213          for (int i = 1; i < node.SubTrees.Count; i++) {
214            stringBuilder.Append("-");
215            stringBuilder.Append(FormatRecursively(node.SubTrees[i]));
216          }
217        }
218      } else if (symbol is Tangent) {
219        stringBuilder.Append("tan(");
220        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
221        stringBuilder.Append(")");
222      } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable) {
223        VariableTreeNode variableTreeNode = node as VariableTreeNode;
224        stringBuilder.Append(variableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
225        stringBuilder.Append("*");
226        stringBuilder.Append(variableTreeNode.VariableName + LagToString(currentLag));
227      } else if (symbol is Power) {
228        stringBuilder.Append("(");
229        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
230        stringBuilder.Append(")^round(");
231        stringBuilder.Append(FormatRecursively(node.SubTrees[1]));
232        stringBuilder.Append(")");
233      } else if (symbol is Root) {
234        stringBuilder.Append("(");
235        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
236        stringBuilder.Append(")^(1 / round(");
237        stringBuilder.Append(FormatRecursively(node.SubTrees[1]));
238        stringBuilder.Append("))");
239      } else if (symbol is Derivative) {
240        stringBuilder.Append("fivePoint(");
241        // f0
242        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
243        stringBuilder.Append(", ");
244        // f1
245        currentLag--;
246        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
247        stringBuilder.Append(", ");
248        // f3
249        currentLag -= 2;
250        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
251        stringBuilder.Append(", ");
252        currentLag--;
253        // f4
254        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
255        stringBuilder.Append(")");
256        currentLag += 4;
257      } else if (symbol is Integral) {
258        var laggedNode = node as LaggedTreeNode;
259        string prevCounterVariable = CurrentIndexVariable;
260        string counterVariable = AllocateIndexVariable();
261        stringBuilder.AppendLine(" sum (map(@(" + counterVariable + ") " + FormatRecursively(node.SubTrees[0]) + ", (" + prevCounterVariable + "+" + laggedNode.Lag + "):" + prevCounterVariable + "))");
262        ReleaseIndexVariable();
263      } else if (symbol is TimeLag) {
264        var laggedNode = node as LaggedTreeNode;
265        currentLag += laggedNode.Lag;
266        stringBuilder.Append(FormatRecursively(node.SubTrees[0]));
267        currentLag -= laggedNode.Lag;
268      } else {
269        stringBuilder.Append("ERROR");
270      }
271
272      stringBuilder.Append(")");
273      return stringBuilder.ToString();
274    }
275
276
277    private string LagToString(int lag) {
278      if (lag < 0) {
279        return "(" + CurrentIndexVariable + "" + lag + ")";
280      } else if (lag > 0) {
281        return "(" + CurrentIndexVariable + "+" + lag + ")";
282      } else return "(" + CurrentIndexVariable + ")";
283    }
284
285  }
286}
Note: See TracBrowser for help on using the repository browser.