Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 16713 was 16702, checked in by bburlacu, 6 years ago

#2866: Add tanh to all formatters except the TSQLExpressionFormatter, since TSQL does not have a TANH function (could be approximated but ugly).

File size: 17.9 KB
RevLine 
[5017]1#region License Information
2/* HeuristicLab
[16565]3 * Copyright (C) 2002-2019 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
[7695]22using System.Globalization;
[14826]23using System.Linq;
[5017]24using System.Text;
[16702]25using HEAL.Attic;
[7695]26using HeuristicLab.Common;
[5017]27using HeuristicLab.Core;
[7695]28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[5017]29
[5745]30namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[5017]31
[5745]32  [Item("MATLAB String Formatter", "String formatter for string representations of symbolic data analysis expressions in MATLAB syntax.")]
[16565]33  [StorableType("ADFB0A37-412D-4DD4-A174-F0103ADD7972")]
[5745]34  public sealed class SymbolicDataAnalysisExpressionMATLABFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
[5431]35    private int currentLag;
[5017]36
[5431]37    [StorableConstructor]
[16565]38    private SymbolicDataAnalysisExpressionMATLABFormatter(StorableConstructorFlag _) : base(_) { }
[5745]39    private SymbolicDataAnalysisExpressionMATLABFormatter(SymbolicDataAnalysisExpressionMATLABFormatter original, Cloner cloner) : base(original, cloner) { }
40    public SymbolicDataAnalysisExpressionMATLABFormatter()
[5019]41      : base() {
[5745]42      Name = ItemName;
43      Description = ItemDescription;
[5017]44    }
[5431]45    public override IDeepCloneable Clone(Cloner cloner) {
[5745]46      return new SymbolicDataAnalysisExpressionMATLABFormatter(this, cloner);
[5431]47    }
48    private int currentIndexNumber;
49    public string CurrentIndexVariable {
50      get {
51        return "i" + currentIndexNumber;
52      }
53    }
54    private void ReleaseIndexVariable() {
55      currentIndexNumber--;
56    }
[5017]57
[5431]58    private string AllocateIndexVariable() {
59      currentIndexNumber++;
60      return CurrentIndexVariable;
61    }
62
[5745]63    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
[5431]64      currentLag = 0;
65      currentIndexNumber = 0;
[7630]66
67      var stringBuilder = new StringBuilder();
68      stringBuilder.AppendLine("rows = ???");
69      stringBuilder.AppendLine(FormatOnlyExpression(symbolicExpressionTree.Root) + ";");
70      stringBuilder.AppendLine();
71      stringBuilder.AppendLine("function y = log_(x)");
72      stringBuilder.AppendLine("  if(x<=0) y = NaN;");
73      stringBuilder.AppendLine("  else     y = log(x);");
74      stringBuilder.AppendLine("  end");
75      stringBuilder.AppendLine("end");
76      stringBuilder.AppendLine();
77      stringBuilder.AppendLine("function y = fivePoint(f0, f1, f3, f4)");
78      stringBuilder.AppendLine("  y = (f0 + 2*f1 - 2*f3 - f4) / 8;");
79      stringBuilder.AppendLine("end");
[14826]80
81      var factorVariableNames =
82        symbolicExpressionTree.IterateNodesPostfix()
83          .OfType<FactorVariableTreeNode>()
84          .Select(n => n.VariableName)
85          .Distinct();
86
87      foreach (var factorVarName in factorVariableNames) {
88        var factorSymb = symbolicExpressionTree.IterateNodesPostfix()
89          .OfType<FactorVariableTreeNode>()
90          .First(n => n.VariableName == factorVarName)
91          .Symbol;
92        stringBuilder.AppendFormat("function y = switch_{0}(val, v)", factorVarName).AppendLine();
93        var values = factorSymb.GetVariableValues(factorVarName).ToArray();
94        stringBuilder.AppendLine("switch val");
95        for (int i = 0; i < values.Length; i++) {
96          stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "  case \"{0}\" y = v({1})", values[i], i).AppendLine();
97        }
98        stringBuilder.AppendLine("end");
99        stringBuilder.AppendLine();
100      }
101
[7630]102      return stringBuilder.ToString();
[5017]103    }
104
[7695]105    public string FormatOnlyExpression(ISymbolicExpressionTreeNode expressionNode) {
[7630]106      var stringBuilder = new StringBuilder();
107      stringBuilder.AppendLine("  for " + CurrentIndexVariable + " = 1:1:rows");
108      stringBuilder.AppendLine("    estimated(" + CurrentIndexVariable + ") = " + FormatRecursively(expressionNode.GetSubtree(0)) + ";");
109      stringBuilder.AppendLine("  end;");
110      return stringBuilder.ToString();
111    }
112
[5745]113    private string FormatRecursively(ISymbolicExpressionTreeNode node) {
114      ISymbol symbol = node.Symbol;
[5017]115      StringBuilder stringBuilder = new StringBuilder();
116
117      if (symbol is ProgramRootSymbol) {
[7630]118        stringBuilder.AppendLine(FormatRecursively(node.GetSubtree(0)));
119      } else if (symbol is StartSymbol)
[5745]120        return FormatRecursively(node.GetSubtree(0));
[7630]121      else if (symbol is Addition) {
122        stringBuilder.Append("(");
[6803]123        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]124          if (i > 0) stringBuilder.Append("+");
[5745]125          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]126        }
[7630]127        stringBuilder.Append(")");
[5017]128      } else if (symbol is And) {
[5021]129        stringBuilder.Append("((");
[6803]130        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]131          if (i > 0) stringBuilder.Append("&");
132          stringBuilder.Append("((");
[5745]133          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]134          stringBuilder.Append(")>0)");
135        }
[7630]136        stringBuilder.Append(")-0.5)*2");
137        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]138      } else if (symbol is Average) {
139        stringBuilder.Append("(1/");
[6803]140        stringBuilder.Append(node.SubtreeCount);
[5017]141        stringBuilder.Append(")*(");
[6803]142        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]143          if (i > 0) stringBuilder.Append("+");
144          stringBuilder.Append("(");
[5745]145          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]146          stringBuilder.Append(")");
147        }
148        stringBuilder.Append(")");
149      } else if (symbol is Constant) {
150        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
[5431]151        stringBuilder.Append(constantTreeNode.Value.ToString(CultureInfo.InvariantCulture));
[5017]152      } else if (symbol is Cosine) {
153        stringBuilder.Append("cos(");
[5745]154        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]155        stringBuilder.Append(")");
156      } else if (symbol is Division) {
[6803]157        if (node.SubtreeCount == 1) {
[5017]158          stringBuilder.Append("1/");
[5745]159          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]160        } else {
[5745]161          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]162          stringBuilder.Append("/(");
[6803]163          for (int i = 1; i < node.SubtreeCount; i++) {
[5017]164            if (i > 1) stringBuilder.Append("*");
[5745]165            stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]166          }
167          stringBuilder.Append(")");
168        }
169      } else if (symbol is Exponential) {
170        stringBuilder.Append("exp(");
[5745]171        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]172        stringBuilder.Append(")");
[7695]173      } else if (symbol is Square) {
174        stringBuilder.Append("(");
175        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
176        stringBuilder.Append(").^2");
177      } else if (symbol is SquareRoot) {
178        stringBuilder.Append("sqrt(");
179        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
180        stringBuilder.Append(")");
[5017]181      } else if (symbol is GreaterThan) {
[5021]182        stringBuilder.Append("((");
[5745]183        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]184        stringBuilder.Append(">");
[5745]185        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[7630]186        stringBuilder.Append(")-0.5)*2");
187        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]188      } else if (symbol is IfThenElse) {
189        stringBuilder.Append("(");
[5745]190        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]191        stringBuilder.Append(">0)*");
[5745]192        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[5017]193        stringBuilder.Append("+");
194        stringBuilder.Append("(");
[5745]195        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5021]196        stringBuilder.Append("<=0)*");
[5745]197        stringBuilder.Append(FormatRecursively(node.GetSubtree(2)));
[5017]198      } else if (symbol is LaggedVariable) {
[5431]199        // this if must be checked before if(symbol is LaggedVariable)
[5017]200        LaggedVariableTreeNode laggedVariableTreeNode = node as LaggedVariableTreeNode;
[5431]201        stringBuilder.Append(laggedVariableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
[5017]202        stringBuilder.Append("*");
[7630]203        stringBuilder.Append(laggedVariableTreeNode.VariableName +
204                             LagToString(currentLag + laggedVariableTreeNode.Lag));
[5017]205      } else if (symbol is LessThan) {
[5021]206        stringBuilder.Append("((");
[5745]207        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]208        stringBuilder.Append("<");
[5745]209        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[7630]210        stringBuilder.Append(")-0.5)*2");
211        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]212      } else if (symbol is Logarithm) {
[5022]213        stringBuilder.Append("log_(");
[5745]214        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]215        stringBuilder.Append(")");
216      } else if (symbol is Multiplication) {
[6803]217        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]218          if (i > 0) stringBuilder.Append("*");
[5745]219          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]220        }
221      } else if (symbol is Not) {
[5745]222        stringBuilder.Append("~(");
223        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
224        stringBuilder.Append(" > 0 )");
[5017]225      } else if (symbol is Or) {
[5021]226        stringBuilder.Append("((");
[6803]227        for (int i = 0; i < node.SubtreeCount; i++) {
[5017]228          if (i > 0) stringBuilder.Append("|");
229          stringBuilder.Append("((");
[5745]230          stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]231          stringBuilder.Append(")>0)");
232        }
[7630]233        stringBuilder.Append(")-0.5)*2");
234        // MATLAB maps false and true to 0 and 1, resp., we map this result to -1.0 and +1.0, resp.
[5017]235      } else if (symbol is Sine) {
236        stringBuilder.Append("sin(");
[5745]237        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]238        stringBuilder.Append(")");
239      } else if (symbol is Subtraction) {
[7653]240        stringBuilder.Append("(");
[6803]241        if (node.SubtreeCount == 1) {
[7653]242          stringBuilder.Append("-");
[5745]243          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]244        } else {
[5745]245          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[6803]246          for (int i = 1; i < node.SubtreeCount; i++) {
[5017]247            stringBuilder.Append("-");
[5745]248            stringBuilder.Append(FormatRecursively(node.GetSubtree(i)));
[5017]249          }
250        }
[7653]251        stringBuilder.Append(")");
[5017]252      } else if (symbol is Tangent) {
253        stringBuilder.Append("tan(");
[5745]254        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5017]255        stringBuilder.Append(")");
[16702]256      } else if (symbol is HyperbolicTangent) {
257        stringBuilder.Append("tanh(");
258        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
259        stringBuilder.Append(")");
[8122]260      } else if (node.Symbol is AiryA) {
261        stringBuilder.Append("airy(");
262        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
263        stringBuilder.Append(")");
264      } else if (node.Symbol is AiryB) {
265        stringBuilder.Append("airy(2, ");
266        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
267        stringBuilder.Append(")");
268      } else if (node.Symbol is Bessel) {
269        stringBuilder.Append("besseli(0.0,");
270        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
271        stringBuilder.Append(")");
272      } else if (node.Symbol is CosineIntegral) {
273        stringBuilder.Append("cosint(");
274        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
275        stringBuilder.Append(")");
276      } else if (node.Symbol is Dawson) {
277        stringBuilder.Append("dawson(");
278        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
279        stringBuilder.Append(")");
280      } else if (node.Symbol is Erf) {
281        stringBuilder.Append("erf(");
282        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
283        stringBuilder.Append(")");
284      } else if (node.Symbol is ExponentialIntegralEi) {
285        stringBuilder.Append("expint(");
286        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
287        stringBuilder.Append(")");
288      } else if (node.Symbol is FresnelCosineIntegral) {
289        stringBuilder.Append("FresnelC(");
290        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
291        stringBuilder.Append(")");
292      } else if (node.Symbol is FresnelSineIntegral) {
293        stringBuilder.Append("FresnelS(");
294        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
295        stringBuilder.Append(")");
296      } else if (node.Symbol is Gamma) {
297        stringBuilder.Append("gamma(");
298        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
299        stringBuilder.Append(")");
300      } else if (node.Symbol is HyperbolicCosineIntegral) {
301        stringBuilder.Append("Chi(");
302        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
303        stringBuilder.Append(")");
304      } else if (node.Symbol is HyperbolicSineIntegral) {
305        stringBuilder.Append("Shi(");
306        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
307        stringBuilder.Append(")");
308      } else if (node.Symbol is Norm) {
309        stringBuilder.Append("normpdf(");
310        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
311        stringBuilder.Append(")");
312      } else if (node.Symbol is Psi) {
313        stringBuilder.Append("psi(");
314        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
315        stringBuilder.Append(")");
316      } else if (node.Symbol is SineIntegral) {
317        stringBuilder.Append("sinint(");
318        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
319        stringBuilder.Append(")");
[5745]320      } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Variable) {
[5017]321        VariableTreeNode variableTreeNode = node as VariableTreeNode;
[5431]322        stringBuilder.Append(variableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
[5017]323        stringBuilder.Append("*");
[5431]324        stringBuilder.Append(variableTreeNode.VariableName + LagToString(currentLag));
[14826]325      } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.FactorVariable) {
326        var factorNode = node as FactorVariableTreeNode;
327        var weights = string.Join(" ", factorNode.Weights.Select(w => w.ToString("G17", CultureInfo.InvariantCulture)));
328        stringBuilder.AppendFormat("switch_{0}(\"{1}\",[{2}])",
329          factorNode.VariableName, factorNode.VariableName, weights)
330          .AppendLine();
331      } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.BinaryFactorVariable) {
332        var factorNode = node as BinaryFactorVariableTreeNode;
333        stringBuilder.AppendFormat(CultureInfo.InvariantCulture,
334          "((strcmp({0},\"{1}\")==1) * {2:G17})", factorNode.VariableName, factorNode.VariableValue, factorNode.Weight);
[5431]335      } else if (symbol is Power) {
336        stringBuilder.Append("(");
[5745]337        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]338        stringBuilder.Append(")^round(");
[5745]339        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[5431]340        stringBuilder.Append(")");
341      } else if (symbol is Root) {
342        stringBuilder.Append("(");
[5745]343        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]344        stringBuilder.Append(")^(1 / round(");
[5745]345        stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
[5431]346        stringBuilder.Append("))");
347      } else if (symbol is Derivative) {
348        stringBuilder.Append("fivePoint(");
349        // f0
[5745]350        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]351        stringBuilder.Append(", ");
352        // f1
353        currentLag--;
[5745]354        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]355        stringBuilder.Append(", ");
356        // f3
357        currentLag -= 2;
[5745]358        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]359        stringBuilder.Append(", ");
360        currentLag--;
361        // f4
[5745]362        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]363        stringBuilder.Append(")");
364        currentLag += 4;
365      } else if (symbol is Integral) {
366        var laggedNode = node as LaggedTreeNode;
367        string prevCounterVariable = CurrentIndexVariable;
368        string counterVariable = AllocateIndexVariable();
[7630]369        stringBuilder.AppendLine(" sum (map(@(" + counterVariable + ") " + FormatRecursively(node.GetSubtree(0)) +
370                                 ", (" + prevCounterVariable + "+" + laggedNode.Lag + "):" + prevCounterVariable +
371                                 "))");
[5431]372        ReleaseIndexVariable();
373      } else if (symbol is TimeLag) {
374        var laggedNode = node as LaggedTreeNode;
375        currentLag += laggedNode.Lag;
[5745]376        stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[5431]377        currentLag -= laggedNode.Lag;
[5019]378      } else {
[5017]379        stringBuilder.Append("ERROR");
380      }
381      return stringBuilder.ToString();
382    }
383
[5431]384
[7695]385    private string LagToString(int lag) {
[5431]386      if (lag < 0) {
387        return "(" + CurrentIndexVariable + "" + lag + ")";
388      } else if (lag > 0) {
389        return "(" + CurrentIndexVariable + "+" + lag + ")";
390      } else return "(" + CurrentIndexVariable + ")";
[5017]391    }
[5431]392
[5017]393  }
394}
Note: See TracBrowser for help on using the repository browser.