Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionLatexFormatter.cs @ 7461

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

#1773 fixed bug in the latex formatter, incorrect parentheses for logical or and and operations

File size: 14.7 KB
RevLine 
[4327]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4327]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
[6975]22using System;
23using System.Collections.Generic;
24using System.Linq;
[4327]25using System.Text;
[6975]26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[4327]29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
[5745]31namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[4969]32  [Item("LaTeX String Formatter", "Formatter for symbolic expression trees for import into LaTeX documents.")]
[5429]33  [StorableClass]
[5745]34  public sealed class SymbolicDataAnalysisExpressionLatexFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
[4969]35    private List<double> constants;
[5428]36    private int currentLag;
[4969]37
[5429]38    [StorableConstructor]
[5745]39    private SymbolicDataAnalysisExpressionLatexFormatter(bool deserializing) : base(deserializing) { }
40    private SymbolicDataAnalysisExpressionLatexFormatter(SymbolicDataAnalysisExpressionLatexFormatter original, Cloner cloner)
[5429]41      : base(original, cloner) {
42      constants = new List<double>(original.constants);
43    }
[5745]44    public SymbolicDataAnalysisExpressionLatexFormatter()
45      : base() {
46      Name = ItemName;
47      Description = ItemDescription;
[4969]48      constants = new List<double>();
49    }
[4327]50
[4900]51    public override IDeepCloneable Clone(Cloner cloner) {
[5745]52      return new SymbolicDataAnalysisExpressionLatexFormatter(this, cloner);
[4900]53    }
54
[5745]55    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
[4327]56      try {
57        StringBuilder strBuilder = new StringBuilder();
[4969]58        constants.Clear();
[4327]59        strBuilder.AppendLine(FormatRecursively(symbolicExpressionTree.Root));
60        return strBuilder.ToString();
61      }
62      catch (NotImplementedException ex) {
63        return ex.Message + Environment.NewLine + ex.StackTrace;
64      }
65    }
66
[5745]67    private string FormatRecursively(ISymbolicExpressionTreeNode node) {
[4327]68      StringBuilder strBuilder = new StringBuilder();
[5428]69      currentLag = 0;
[4327]70      FormatBegin(node, strBuilder);
71
[6803]72      if (node.SubtreeCount > 0) {
[5745]73        strBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[4327]74      }
[7140]75      int i = 1;
[5745]76      foreach (SymbolicExpressionTreeNode subTree in node.Subtrees.Skip(1)) {
[7140]77        FormatSep(node, strBuilder, i);
[4327]78        // format the whole subtree
79        strBuilder.Append(FormatRecursively(subTree));
[7140]80        i++;
[4327]81      }
82
83      FormatEnd(node, strBuilder);
84
85      return strBuilder.ToString();
86    }
87
[5745]88    private void FormatBegin(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
[4327]89      if (node.Symbol is Addition) {
[7446]90        strBuilder.Append(@" \left( ");
[4327]91      } else if (node.Symbol is Subtraction) {
[6803]92        if (node.SubtreeCount == 1) {
[7446]93          strBuilder.Append(@"- \left( ");
[5428]94        } else {
[7446]95          strBuilder.Append(@" \left( ");
[5428]96        }
[4327]97      } else if (node.Symbol is Multiplication) {
98      } else if (node.Symbol is Division) {
[6803]99        if (node.SubtreeCount == 1) {
[5428]100          strBuilder.Append(@" \cfrac{1}{");
101        } else {
102          strBuilder.Append(@" \cfrac{ ");
103        }
[4969]104      } else if (node.Symbol is Average) {
[5428]105        // skip output of (1/1) if only one subtree
[6803]106        if (node.SubtreeCount > 1) {
107          strBuilder.Append(@" \cfrac{1}{" + node.SubtreeCount + @"}");
[5428]108        }
[7446]109        strBuilder.Append(@" \left( ");
[4969]110      } else if (node.Symbol is Logarithm) {
[7446]111        strBuilder.Append(@"\log \left( ");
[4969]112      } else if (node.Symbol is Exponential) {
[7446]113        strBuilder.Append(@"\exp \left( ");
[4969]114      } else if (node.Symbol is Sine) {
[7446]115        strBuilder.Append(@"\sin \left( ");
[4969]116      } else if (node.Symbol is Cosine) {
[7446]117        strBuilder.Append(@"\cos \left( ");
[4969]118      } else if (node.Symbol is Tangent) {
[7446]119        strBuilder.Append(@"\tan \left( ");
[4969]120      } else if (node.Symbol is GreaterThan) {
[7446]121        strBuilder.Append(@"  \left( ");
[4969]122      } else if (node.Symbol is LessThan) {
[7446]123        strBuilder.Append(@"  \left( ");
[4969]124      } else if (node.Symbol is And) {
[7451]125        strBuilder.Append(@"  \left( \left( ");
[4969]126      } else if (node.Symbol is Or) {
[7451]127        strBuilder.Append(@"   \left( \left( ");
[4969]128      } else if (node.Symbol is Not) {
[7446]129        strBuilder.Append(@" \neg \left( ");
[4969]130      } else if (node.Symbol is IfThenElse) {
[7446]131        strBuilder.Append(@" \operatorname{if}  \left( ");
[4327]132      } else if (node.Symbol is Constant) {
[5428]133        strBuilder.Append("c_{" + constants.Count + "} ");
[4969]134        var constNode = node as ConstantTreeNode;
135        constants.Add(constNode.Value);
[5428]136      } else if (node.Symbol is LaggedVariable) {
137        var laggedVarNode = node as LaggedVariableTreeNode;
[7038]138        if (!laggedVarNode.Weight.IsAlmost(1.0)) {
139          strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
140          constants.Add(laggedVarNode.Weight);
141        }
142        strBuilder.Append(EscapeLatexString(laggedVarNode.VariableName));
[5428]143        strBuilder.Append(LagToString(currentLag + laggedVarNode.Lag));
[7038]144
145      } else if (node.Symbol is Variable) {
[4327]146        var varNode = node as VariableTreeNode;
[7038]147        if (!varNode.Weight.IsAlmost((1.0))) {
148          strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
149          constants.Add(varNode.Weight);
150        }
151        strBuilder.Append(EscapeLatexString(varNode.VariableName));
[5428]152        strBuilder.Append(LagToString(currentLag));
[4327]153      } else if (node.Symbol is ProgramRootSymbol) {
[7446]154        strBuilder
155          .AppendLine("\\begin{align*}")
156          .AppendLine("\\nonumber");
[4327]157      } else if (node.Symbol is Defun) {
158        var defunNode = node as DefunTreeNode;
[4969]159        strBuilder.Append(defunNode.FunctionName + " & = ");
[4327]160      } else if (node.Symbol is InvokeFunction) {
161        var invokeNode = node as InvokeFunctionTreeNode;
[7446]162        strBuilder.Append(invokeNode.Symbol.FunctionName + @" \left( ");
[4327]163      } else if (node.Symbol is StartSymbol) {
[4969]164        strBuilder.Append("Result & = ");
[4900]165      } else if (node.Symbol is Argument) {
[4327]166        var argSym = node.Symbol as Argument;
[4900]167        strBuilder.Append(" ARG+" + argSym.ArgumentIndex + " ");
[5428]168      } else if (node.Symbol is Derivative) {
[7446]169        strBuilder.Append(@" \cfrac{d \left( ");
[5428]170      } else if (node.Symbol is TimeLag) {
171        var laggedNode = node as ILaggedTreeNode;
172        currentLag += laggedNode.Lag;
173      } else if (node.Symbol is Power) {
[7446]174        strBuilder.Append(@" \left( ");
[5428]175      } else if (node.Symbol is Root) {
[7446]176        strBuilder.Append(@" \left( ");
[5428]177      } else if (node.Symbol is Integral) {
178        // actually a new variable for t is needed in all subtrees (TODO)
179        var laggedTreeNode = node as ILaggedTreeNode;
[7446]180        strBuilder.Append(@"\sum_{t=" + (laggedTreeNode.Lag + currentLag) + @"}^0 \left( ");
[5468]181      } else if (node.Symbol is VariableCondition) {
182        var conditionTreeNode = node as VariableConditionTreeNode;
[7038]183        string p = @"1 /  1 + \exp  - c_{" + constants.Count + "} ";
[5468]184        constants.Add(conditionTreeNode.Slope);
[7038]185        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"}   ";
[5468]186        constants.Add(conditionTreeNode.Threshold);
[7446]187        strBuilder.Append(@" \left( " + p + @"\cdot ");
[4327]188      } else {
189        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
190      }
191    }
192
[7140]193    private void FormatSep(ISymbolicExpressionTreeNode node, StringBuilder strBuilder, int step) {
[4327]194      if (node.Symbol is Addition) {
195        strBuilder.Append(" + ");
196      } else if (node.Symbol is Subtraction) {
197        strBuilder.Append(" - ");
198      } else if (node.Symbol is Multiplication) {
[5428]199        strBuilder.Append(@" \cdot ");
[4327]200      } else if (node.Symbol is Division) {
[7140]201        if (step + 1 == node.SubtreeCount)
202          strBuilder.Append(@"}{");
203        else
204          strBuilder.Append(@" }{ \cfrac{ ");
[4969]205      } else if (node.Symbol is Average) {
206        strBuilder.Append(@" + ");
207      } else if (node.Symbol is Logarithm) {
208        throw new InvalidOperationException();
209      } else if (node.Symbol is Exponential) {
210        throw new InvalidOperationException();
211      } else if (node.Symbol is Sine) {
212        throw new InvalidOperationException();
213      } else if (node.Symbol is Cosine) {
214        throw new InvalidOperationException();
215      } else if (node.Symbol is Tangent) {
216        throw new InvalidOperationException();
217      } else if (node.Symbol is GreaterThan) {
218        strBuilder.Append(@" > ");
219      } else if (node.Symbol is LessThan) {
220        strBuilder.Append(@" < ");
221      } else if (node.Symbol is And) {
[7446]222        strBuilder.Append(@" > 0  \right) \land \left(");
[4969]223      } else if (node.Symbol is Or) {
[7446]224        strBuilder.Append(@" > 0  \right) \lor \left(");
[4969]225      } else if (node.Symbol is Not) {
226        throw new InvalidOperationException();
227      } else if (node.Symbol is IfThenElse) {
[7446]228        strBuilder.Append(@" , ");
[4327]229      } else if (node.Symbol is ProgramRootSymbol) {
230        strBuilder.Append(@"\\" + Environment.NewLine);
231      } else if (node.Symbol is Defun) {
232      } else if (node.Symbol is InvokeFunction) {
233        strBuilder.Append(" , ");
234      } else if (node.Symbol is StartSymbol) {
[4969]235        strBuilder.Append(@"\\" + Environment.NewLine + " & ");
[5428]236      } else if (node.Symbol is Power) {
[7446]237        strBuilder.Append(@"\right) ^ { \operatorname{round} \left(");
[5428]238      } else if (node.Symbol is Root) {
[7446]239        strBuilder.Append(@"\right) ^ {  \cfrac{1}{ \operatorname{round} \left(");
[5468]240      } else if (node.Symbol is VariableCondition) {
241        var conditionTreeNode = node as VariableConditionTreeNode;
[7446]242        string p = @"1 / \left( 1 + \exp \left( - c_{" + constants.Count + "} ";
[5468]243        constants.Add(conditionTreeNode.Slope);
[7446]244        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"} \right) \right) \right)   ";
[5468]245        constants.Add(conditionTreeNode.Threshold);
[7446]246        strBuilder.Append(@" +  \left( 1 - " + p + @" \right) \cdot ");
[4327]247      } else {
248        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
249      }
250    }
251
[5745]252    private void FormatEnd(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
[4327]253      if (node.Symbol is Addition) {
[7446]254        strBuilder.Append(@" \right) ");
[4327]255      } else if (node.Symbol is Subtraction) {
[7446]256        strBuilder.Append(@" \right) ");
[4327]257      } else if (node.Symbol is Multiplication) {
258      } else if (node.Symbol is Division) {
[7140]259        strBuilder.Append(" } ");
260        for (int i = 2; i < node.SubtreeCount; i++)
[5428]261          strBuilder.Append(" } ");
[4969]262      } else if (node.Symbol is Average) {
[7446]263        strBuilder.Append(@" \right) ");
[4969]264      } else if (node.Symbol is Logarithm) {
[7446]265        strBuilder.Append(@" \right) ");
[4969]266      } else if (node.Symbol is Exponential) {
[7446]267        strBuilder.Append(@" \right) ");
[4969]268      } else if (node.Symbol is Sine) {
[7446]269        strBuilder.Append(@" \right) ");
[4969]270      } else if (node.Symbol is Cosine) {
[7446]271        strBuilder.Append(@" \right) ");
[4969]272      } else if (node.Symbol is Tangent) {
[7446]273        strBuilder.Append(@" \right) ");
[4969]274      } else if (node.Symbol is GreaterThan) {
[7446]275        strBuilder.Append(@" \right) ");
[4969]276      } else if (node.Symbol is LessThan) {
[7446]277        strBuilder.Append(@" \right) ");
[4969]278      } else if (node.Symbol is And) {
[7446]279        strBuilder.Append(@" > 0 \right) \right) ");
[4969]280      } else if (node.Symbol is Or) {
[7446]281        strBuilder.Append(@" > 0 \right) \right) ");
[4969]282      } else if (node.Symbol is Not) {
[7446]283        strBuilder.Append(@" \right) ");
[4969]284      } else if (node.Symbol is IfThenElse) {
[7446]285        strBuilder.Append(@" \right) ");
[4327]286      } else if (node.Symbol is Constant) {
[5428]287      } else if (node.Symbol is LaggedVariable) {
[7038]288      } else if (node.Symbol is Variable) {
[4327]289      } else if (node.Symbol is ProgramRootSymbol) {
[7446]290        strBuilder
291          .AppendLine("\\end{align*}")
292          .AppendLine("\\begin{align*}")
293          .AppendLine("\\nonumber");
[4969]294        // output all constant values
295        if (constants.Count > 0) {
296          int i = 0;
297          foreach (var constant in constants) {
[7446]298            // replace "." with ".&" to align decimal points
299            var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant);
[7451]300            if (!constStr.Contains(".")) constStr = constStr + ".0";
[7446]301            constStr = constStr.Replace(".", "\\negthickspace&.");  // fix problem in rendering of aligned expressions
302            strBuilder.Append("c_{" + i + "}& = & " + constStr);
303            strBuilder.Append(@"\\");
[4969]304            i++;
305          }
306        }
[7446]307        strBuilder.AppendLine("\\end{align*}");
[4327]308      } else if (node.Symbol is Defun) {
309      } else if (node.Symbol is InvokeFunction) {
[7446]310        strBuilder.Append(@" \right) ");
[4327]311      } else if (node.Symbol is StartSymbol) {
312      } else if (node.Symbol is Argument) {
[5428]313      } else if (node.Symbol is Derivative) {
[7446]314        strBuilder.Append(@" \right) }{dt} ");
[5428]315      } else if (node.Symbol is TimeLag) {
316        var laggedNode = node as ILaggedTreeNode;
317        currentLag -= laggedNode.Lag;
318      } else if (node.Symbol is Power) {
[7446]319        strBuilder.Append(@" \right) } ");
[5428]320      } else if (node.Symbol is Root) {
[7446]321        strBuilder.Append(@" \right) } } ");
[5428]322      } else if (node.Symbol is Integral) {
[7446]323        strBuilder.Append(@" \right) ");
[5468]324      } else if (node.Symbol is VariableCondition) {
[7446]325        strBuilder.Append(@"\right) ");
[4327]326      } else {
327        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
328      }
329    }
[6975]330
[5428]331    private string LagToString(int lag) {
332      if (lag < 0) {
333        return "(t" + lag + ")";
334      } else if (lag > 0) {
335        return "(t+" + lag + ")";
[7038]336      } else return "";
[5428]337    }
[6975]338
339    private string EscapeLatexString(string s) {
[7446]340      return "\\text{" +
341        s
342         .Replace("\\", "\\\\")
343         .Replace("{", "\\{")
344         .Replace("}", "\\}")
345         .Replace("%", "\\%")
346        + "}";
[6975]347    }
[4327]348  }
349}
Note: See TracBrowser for help on using the repository browser.