Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveHiveEngine/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionLatexFormatter.cs @ 11247

Last change on this file since 11247 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

File size: 13.9 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("% needs \\usepackage{amsmath}");
60        strBuilder.AppendLine("\\begin{align*}");
61        strBuilder.AppendLine("\\nonumber");
62        strBuilder.AppendLine(FormatRecursively(symbolicExpressionTree.Root));
63        strBuilder.AppendLine("\\end{align*}");
64        return strBuilder.ToString();
65      }
66      catch (NotImplementedException ex) {
67        return ex.Message + Environment.NewLine + ex.StackTrace;
68      }
69    }
70
71    private string FormatRecursively(ISymbolicExpressionTreeNode node) {
72      StringBuilder strBuilder = new StringBuilder();
73      currentLag = 0;
74      FormatBegin(node, strBuilder);
75
76      if (node.SubtreeCount > 0) {
77        strBuilder.Append(FormatRecursively(node.GetSubtree(0)));
78      }
79      int i = 1;
80      foreach (SymbolicExpressionTreeNode subTree in node.Subtrees.Skip(1)) {
81        FormatSep(node, strBuilder, i);
82        // format the whole subtree
83        strBuilder.Append(FormatRecursively(subTree));
84        i++;
85      }
86
87      FormatEnd(node, strBuilder);
88
89      return strBuilder.ToString();
90    }
91
92    private void FormatBegin(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
93      if (node.Symbol is Addition) {
94        strBuilder.Append(@" ( ");
95      } else if (node.Symbol is Subtraction) {
96        if (node.SubtreeCount == 1) {
97          strBuilder.Append(@"- ( ");
98        } else {
99          strBuilder.Append(@" ( ");
100        }
101      } else if (node.Symbol is Multiplication) {
102      } else if (node.Symbol is Division) {
103        if (node.SubtreeCount == 1) {
104          strBuilder.Append(@" \cfrac{1}{");
105        } else {
106          strBuilder.Append(@" \cfrac{ ");
107        }
108      } else if (node.Symbol is Average) {
109        // skip output of (1/1) if only one subtree
110        if (node.SubtreeCount > 1) {
111          strBuilder.Append(@" \cfrac{1}{" + node.SubtreeCount + @"}");
112        }
113        strBuilder.Append(@" ( ");
114      } else if (node.Symbol is Logarithm) {
115        strBuilder.Append(@"\log ( ");
116      } else if (node.Symbol is Exponential) {
117        strBuilder.Append(@"\exp ( ");
118      } else if (node.Symbol is Sine) {
119        strBuilder.Append(@"\sin ( ");
120      } else if (node.Symbol is Cosine) {
121        strBuilder.Append(@"\cos ( ");
122      } else if (node.Symbol is Tangent) {
123        strBuilder.Append(@"\tan ( ");
124      } else if (node.Symbol is GreaterThan) {
125        strBuilder.Append(@"  ( ");
126      } else if (node.Symbol is LessThan) {
127        strBuilder.Append(@"  ( ");
128      } else if (node.Symbol is And) {
129        strBuilder.Append(@"   ( ");
130      } else if (node.Symbol is Or) {
131        strBuilder.Append(@"   ( ");
132      } else if (node.Symbol is Not) {
133        strBuilder.Append(@" \neg ( ");
134      } else if (node.Symbol is IfThenElse) {
135        strBuilder.Append(@" \operatorname{if}  ( 0 < ");
136      } else if (node.Symbol is Constant) {
137        strBuilder.Append("c_{" + constants.Count + "} ");
138        var constNode = node as ConstantTreeNode;
139        constants.Add(constNode.Value);
140      } else if (node.Symbol is LaggedVariable) {
141        var laggedVarNode = node as LaggedVariableTreeNode;
142        if (!laggedVarNode.Weight.IsAlmost(1.0)) {
143          strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
144          constants.Add(laggedVarNode.Weight);
145        }
146        strBuilder.Append(EscapeLatexString(laggedVarNode.VariableName));
147        strBuilder.Append(LagToString(currentLag + laggedVarNode.Lag));
148
149      } else if (node.Symbol is Variable) {
150        var varNode = node as VariableTreeNode;
151        if (!varNode.Weight.IsAlmost((1.0))) {
152          strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
153          constants.Add(varNode.Weight);
154        }
155        strBuilder.Append(EscapeLatexString(varNode.VariableName));
156        strBuilder.Append(LagToString(currentLag));
157      } else if (node.Symbol is ProgramRootSymbol) {
158      } else if (node.Symbol is Defun) {
159        var defunNode = node as DefunTreeNode;
160        strBuilder.Append(defunNode.FunctionName + " & = ");
161      } else if (node.Symbol is InvokeFunction) {
162        var invokeNode = node as InvokeFunctionTreeNode;
163        strBuilder.Append(invokeNode.Symbol.FunctionName + @" ( ");
164      } else if (node.Symbol is StartSymbol) {
165        strBuilder.Append("Result & = ");
166      } else if (node.Symbol is Argument) {
167        var argSym = node.Symbol as Argument;
168        strBuilder.Append(" ARG+" + argSym.ArgumentIndex + " ");
169      } else if (node.Symbol is Derivative) {
170        strBuilder.Append(@" \cfrac{d ( ");
171      } else if (node.Symbol is TimeLag) {
172        var laggedNode = node as ILaggedTreeNode;
173        currentLag += laggedNode.Lag;
174      } else if (node.Symbol is Power) {
175        strBuilder.Append(@" ( ");
176      } else if (node.Symbol is Root) {
177        strBuilder.Append(@" ( ");
178      } else if (node.Symbol is Integral) {
179        // actually a new variable for t is needed in all subtrees (TODO)
180        var laggedTreeNode = node as ILaggedTreeNode;
181        strBuilder.Append(@"\sum_{t=" + (laggedTreeNode.Lag + currentLag) + @"}^0 ( ");
182      } else if (node.Symbol is VariableCondition) {
183        var conditionTreeNode = node as VariableConditionTreeNode;
184        string p = @"1 /  1 + \exp  - c_{" + constants.Count + "} ";
185        constants.Add(conditionTreeNode.Slope);
186        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"}   ";
187        constants.Add(conditionTreeNode.Threshold);
188        strBuilder.Append(@" ( " + p + @"\cdot ");
189      } else {
190        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
191      }
192    }
193
194    private void FormatSep(ISymbolicExpressionTreeNode node, StringBuilder strBuilder, int step) {
195      if (node.Symbol is Addition) {
196        strBuilder.Append(" + ");
197      } else if (node.Symbol is Subtraction) {
198        strBuilder.Append(" - ");
199      } else if (node.Symbol is Multiplication) {
200        strBuilder.Append(@" \cdot ");
201      } else if (node.Symbol is Division) {
202        if (step + 1 == node.SubtreeCount)
203          strBuilder.Append(@"}{");
204        else
205          strBuilder.Append(@" }{ \cfrac{ ");
206      } else if (node.Symbol is Average) {
207        strBuilder.Append(@" + ");
208      } else if (node.Symbol is Logarithm) {
209        throw new InvalidOperationException();
210      } else if (node.Symbol is Exponential) {
211        throw new InvalidOperationException();
212      } else if (node.Symbol is Sine) {
213        throw new InvalidOperationException();
214      } else if (node.Symbol is Cosine) {
215        throw new InvalidOperationException();
216      } else if (node.Symbol is Tangent) {
217        throw new InvalidOperationException();
218      } else if (node.Symbol is GreaterThan) {
219        strBuilder.Append(@" > ");
220      } else if (node.Symbol is LessThan) {
221        strBuilder.Append(@" < ");
222      } else if (node.Symbol is And) {
223        strBuilder.Append(@" > 0  ) \land (");
224      } else if (node.Symbol is Or) {
225        strBuilder.Append(@" > 0  ) \lor (");
226      } else if (node.Symbol is Not) {
227        throw new InvalidOperationException();
228      } else if (node.Symbol is IfThenElse) {
229        strBuilder.Append(@" ) , (");
230      } else if (node.Symbol is ProgramRootSymbol) {
231        strBuilder.Append(@"\\" + Environment.NewLine);
232      } else if (node.Symbol is Defun) {
233      } else if (node.Symbol is InvokeFunction) {
234        strBuilder.Append(" , ");
235      } else if (node.Symbol is StartSymbol) {
236        strBuilder.Append(@"\\" + Environment.NewLine + " & ");
237      } else if (node.Symbol is Power) {
238        strBuilder.Append(@") ^ { \operatorname{round} (");
239      } else if (node.Symbol is Root) {
240        strBuilder.Append(@") ^ {  \cfrac{1}{ \operatorname{round} (");
241      } else if (node.Symbol is VariableCondition) {
242        var conditionTreeNode = node as VariableConditionTreeNode;
243        string p = @"1 / ( 1 + \exp ( - c_{" + constants.Count + "} ";
244        constants.Add(conditionTreeNode.Slope);
245        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"} ) ) )   ";
246        constants.Add(conditionTreeNode.Threshold);
247        strBuilder.Append(@" +  ( 1 - " + p + @" ) \cdot ");
248      } else {
249        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
250      }
251    }
252
253    private void FormatEnd(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
254      if (node.Symbol is Addition) {
255        strBuilder.Append(@" ) ");
256      } else if (node.Symbol is Subtraction) {
257        strBuilder.Append(@" ) ");
258      } else if (node.Symbol is Multiplication) {
259      } else if (node.Symbol is Division) {
260        strBuilder.Append(" } ");
261        for (int i = 2; i < node.SubtreeCount; i++)
262          strBuilder.Append(" } ");
263      } else if (node.Symbol is Average) {
264        strBuilder.Append(@" ) ");
265      } else if (node.Symbol is Logarithm) {
266        strBuilder.Append(@" ) ");
267      } else if (node.Symbol is Exponential) {
268        strBuilder.Append(@" ) ");
269      } else if (node.Symbol is Sine) {
270        strBuilder.Append(@" ) ");
271      } else if (node.Symbol is Cosine) {
272        strBuilder.Append(@" ) ");
273      } else if (node.Symbol is Tangent) {
274        strBuilder.Append(@" ) ");
275      } else if (node.Symbol is GreaterThan) {
276        strBuilder.Append(@" ) ");
277      } else if (node.Symbol is LessThan) {
278        strBuilder.Append(@" ) ");
279      } else if (node.Symbol is And) {
280        strBuilder.Append(@" > 0 ) ) ");
281      } else if (node.Symbol is Or) {
282        strBuilder.Append(@" > 0 ) ) ");
283      } else if (node.Symbol is Not) {
284        strBuilder.Append(@" ) ");
285      } else if (node.Symbol is IfThenElse) {
286        strBuilder.Append(@" ) ) ");
287      } else if (node.Symbol is Constant) {
288      } else if (node.Symbol is LaggedVariable) {
289      } else if (node.Symbol is Variable) {
290      } else if (node.Symbol is ProgramRootSymbol) {
291        // output all constant values
292        if (constants.Count > 0) {
293          int i = 0;
294          foreach (var constant in constants) {
295            strBuilder.AppendLine(@"\\");
296            strBuilder.Append("c_{" + i + "} & = " + constant);
297            i++;
298          }
299        }
300      } else if (node.Symbol is Defun) {
301      } else if (node.Symbol is InvokeFunction) {
302        strBuilder.Append(@" ) ");
303      } else if (node.Symbol is StartSymbol) {
304      } else if (node.Symbol is Argument) {
305      } else if (node.Symbol is Derivative) {
306        strBuilder.Append(@" ) }{dt} ");
307      } else if (node.Symbol is TimeLag) {
308        var laggedNode = node as ILaggedTreeNode;
309        currentLag -= laggedNode.Lag;
310      } else if (node.Symbol is Power) {
311        strBuilder.Append(@" ) } ");
312      } else if (node.Symbol is Root) {
313        strBuilder.Append(@" ) } ) } ");
314      } else if (node.Symbol is Integral) {
315        var laggedTreeNode = node as ILaggedTreeNode;
316        strBuilder.Append(@" ) ");
317      } else if (node.Symbol is VariableCondition) {
318        strBuilder.Append(@"\left) ");
319      } else {
320        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
321      }
322    }
323
324    private string LagToString(int lag) {
325      if (lag < 0) {
326        return "(t" + lag + ")";
327      } else if (lag > 0) {
328        return "(t+" + lag + ")";
329      } else return "";
330    }
331
332    private string EscapeLatexString(string s) {
333      return s.Replace(@"_", @"\_");
334    }
335  }
336}
Note: See TracBrowser for help on using the repository browser.