Free cookie consent management tool by TermsFeed Policy Generator

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

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

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

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