Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10188 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 19.7 KB
RevLine 
[4327]1#region License Information
2/* HeuristicLab
[9456]3 * Copyright (C) 2002-2013 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 {
[8798]35    private readonly List<double> constants;
36    private int targetCount;
[5428]37    private int currentLag;
[4969]38
[5429]39    [StorableConstructor]
[5745]40    private SymbolicDataAnalysisExpressionLatexFormatter(bool deserializing) : base(deserializing) { }
41    private SymbolicDataAnalysisExpressionLatexFormatter(SymbolicDataAnalysisExpressionLatexFormatter original, Cloner cloner)
[5429]42      : base(original, cloner) {
43      constants = new List<double>(original.constants);
44    }
[5745]45    public SymbolicDataAnalysisExpressionLatexFormatter()
46      : base() {
47      Name = ItemName;
48      Description = ItemDescription;
[4969]49      constants = new List<double>();
50    }
[4327]51
[4900]52    public override IDeepCloneable Clone(Cloner cloner) {
[5745]53      return new SymbolicDataAnalysisExpressionLatexFormatter(this, cloner);
[4900]54    }
55
[5745]56    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
[4327]57      try {
58        StringBuilder strBuilder = new StringBuilder();
[4969]59        constants.Clear();
[4327]60        strBuilder.AppendLine(FormatRecursively(symbolicExpressionTree.Root));
61        return strBuilder.ToString();
62      }
63      catch (NotImplementedException ex) {
64        return ex.Message + Environment.NewLine + ex.StackTrace;
65      }
66    }
67
[5745]68    private string FormatRecursively(ISymbolicExpressionTreeNode node) {
[4327]69      StringBuilder strBuilder = new StringBuilder();
[5428]70      currentLag = 0;
[4327]71      FormatBegin(node, strBuilder);
72
[6803]73      if (node.SubtreeCount > 0) {
[5745]74        strBuilder.Append(FormatRecursively(node.GetSubtree(0)));
[4327]75      }
[7140]76      int i = 1;
[5745]77      foreach (SymbolicExpressionTreeNode subTree in node.Subtrees.Skip(1)) {
[7140]78        FormatSep(node, strBuilder, i);
[4327]79        // format the whole subtree
80        strBuilder.Append(FormatRecursively(subTree));
[7140]81        i++;
[4327]82      }
83
84      FormatEnd(node, strBuilder);
85
86      return strBuilder.ToString();
87    }
88
[5745]89    private void FormatBegin(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
[4327]90      if (node.Symbol is Addition) {
[7446]91        strBuilder.Append(@" \left( ");
[4327]92      } else if (node.Symbol is Subtraction) {
[6803]93        if (node.SubtreeCount == 1) {
[7446]94          strBuilder.Append(@"- \left( ");
[5428]95        } else {
[7446]96          strBuilder.Append(@" \left( ");
[5428]97        }
[4327]98      } else if (node.Symbol is Multiplication) {
99      } else if (node.Symbol is Division) {
[6803]100        if (node.SubtreeCount == 1) {
[8798]101          strBuilder.Append(@" \cfrac{1");
[5428]102        } else {
103          strBuilder.Append(@" \cfrac{ ");
104        }
[4969]105      } else if (node.Symbol is Average) {
[5428]106        // skip output of (1/1) if only one subtree
[6803]107        if (node.SubtreeCount > 1) {
108          strBuilder.Append(@" \cfrac{1}{" + node.SubtreeCount + @"}");
[5428]109        }
[7446]110        strBuilder.Append(@" \left( ");
[4969]111      } else if (node.Symbol is Logarithm) {
[7446]112        strBuilder.Append(@"\log \left( ");
[4969]113      } else if (node.Symbol is Exponential) {
[7446]114        strBuilder.Append(@"\exp \left( ");
[7695]115      } else if (node.Symbol is Square) {
116        strBuilder.Append(@"\left(");
117      } else if (node.Symbol is SquareRoot) {
118        strBuilder.Append(@"\sqrt{");
[4969]119      } else if (node.Symbol is Sine) {
[7446]120        strBuilder.Append(@"\sin \left( ");
[4969]121      } else if (node.Symbol is Cosine) {
[7446]122        strBuilder.Append(@"\cos \left( ");
[4969]123      } else if (node.Symbol is Tangent) {
[7446]124        strBuilder.Append(@"\tan \left( ");
[7696]125      } else if (node.Symbol is AiryA) {
126        strBuilder.Append(@"\operatorname{airy}_a \left( ");
127      } else if (node.Symbol is AiryB) {
128        strBuilder.Append(@"\operatorname{airy}_b \left( ");
129      } else if (node.Symbol is Bessel) {
130        strBuilder.Append(@"\operatorname{bessel}_1 \left( ");
131      } else if (node.Symbol is CosineIntegral) {
132        strBuilder.Append(@"\operatorname{cosInt} \left( ");
133      } else if (node.Symbol is Dawson) {
134        strBuilder.Append(@"\operatorname{dawson} \left( ");
135      } else if (node.Symbol is Erf) {
136        strBuilder.Append(@"\operatorname{erf} \left( ");
137      } else if (node.Symbol is ExponentialIntegralEi) {
138        strBuilder.Append(@"\operatorname{expInt}_i \left( ");
139      } else if (node.Symbol is FresnelCosineIntegral) {
[7708]140        strBuilder.Append(@"\operatorname{fresnel}_\operatorname{cosInt} \left( ");
[7696]141      } else if (node.Symbol is FresnelSineIntegral) {
[7708]142        strBuilder.Append(@"\operatorname{fresnel}_\operatorname{sinInt} \left( ");
[7696]143      } else if (node.Symbol is Gamma) {
144        strBuilder.Append(@"\Gamma \left( ");
145      } else if (node.Symbol is HyperbolicCosineIntegral) {
146        strBuilder.Append(@"\operatorname{hypCosInt} \left( ");
147      } else if (node.Symbol is HyperbolicSineIntegral) {
148        strBuilder.Append(@"\operatorname{hypSinInt} \left( ");
[7697]149      } else if (node.Symbol is Norm) {
150        strBuilder.Append(@"\operatorname{norm} \left( ");
[7696]151      } else if (node.Symbol is Psi) {
152        strBuilder.Append(@"\operatorname{digamma} \left( ");
153      } else if (node.Symbol is SineIntegral) {
154        strBuilder.Append(@"\operatorname{sinInt} \left( ");
[4969]155      } else if (node.Symbol is GreaterThan) {
[7446]156        strBuilder.Append(@"  \left( ");
[4969]157      } else if (node.Symbol is LessThan) {
[7446]158        strBuilder.Append(@"  \left( ");
[4969]159      } else if (node.Symbol is And) {
[7451]160        strBuilder.Append(@"  \left( \left( ");
[4969]161      } else if (node.Symbol is Or) {
[7451]162        strBuilder.Append(@"   \left( \left( ");
[4969]163      } else if (node.Symbol is Not) {
[7446]164        strBuilder.Append(@" \neg \left( ");
[4969]165      } else if (node.Symbol is IfThenElse) {
[7446]166        strBuilder.Append(@" \operatorname{if}  \left( ");
[4327]167      } else if (node.Symbol is Constant) {
[5428]168        strBuilder.Append("c_{" + constants.Count + "} ");
[4969]169        var constNode = node as ConstantTreeNode;
170        constants.Add(constNode.Value);
[5428]171      } else if (node.Symbol is LaggedVariable) {
172        var laggedVarNode = node as LaggedVariableTreeNode;
[7038]173        if (!laggedVarNode.Weight.IsAlmost(1.0)) {
174          strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
175          constants.Add(laggedVarNode.Weight);
176        }
177        strBuilder.Append(EscapeLatexString(laggedVarNode.VariableName));
[5428]178        strBuilder.Append(LagToString(currentLag + laggedVarNode.Lag));
[7038]179
180      } else if (node.Symbol is Variable) {
[4327]181        var varNode = node as VariableTreeNode;
[7038]182        if (!varNode.Weight.IsAlmost((1.0))) {
183          strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
184          constants.Add(varNode.Weight);
185        }
186        strBuilder.Append(EscapeLatexString(varNode.VariableName));
[5428]187        strBuilder.Append(LagToString(currentLag));
[4327]188      } else if (node.Symbol is ProgramRootSymbol) {
[7446]189        strBuilder
190          .AppendLine("\\begin{align*}")
191          .AppendLine("\\nonumber");
[4327]192      } else if (node.Symbol is Defun) {
193        var defunNode = node as DefunTreeNode;
[4969]194        strBuilder.Append(defunNode.FunctionName + " & = ");
[4327]195      } else if (node.Symbol is InvokeFunction) {
196        var invokeNode = node as InvokeFunctionTreeNode;
[7446]197        strBuilder.Append(invokeNode.Symbol.FunctionName + @" \left( ");
[4327]198      } else if (node.Symbol is StartSymbol) {
[8798]199        strBuilder.Append("target_" + (targetCount++) + "(t) & = ");
[4900]200      } else if (node.Symbol is Argument) {
[4327]201        var argSym = node.Symbol as Argument;
[4900]202        strBuilder.Append(" ARG+" + argSym.ArgumentIndex + " ");
[5428]203      } else if (node.Symbol is Derivative) {
[7446]204        strBuilder.Append(@" \cfrac{d \left( ");
[5428]205      } else if (node.Symbol is TimeLag) {
206        var laggedNode = node as ILaggedTreeNode;
207        currentLag += laggedNode.Lag;
208      } else if (node.Symbol is Power) {
[7446]209        strBuilder.Append(@" \left( ");
[5428]210      } else if (node.Symbol is Root) {
[7446]211        strBuilder.Append(@" \left( ");
[5428]212      } else if (node.Symbol is Integral) {
213        // actually a new variable for t is needed in all subtrees (TODO)
214        var laggedTreeNode = node as ILaggedTreeNode;
[7446]215        strBuilder.Append(@"\sum_{t=" + (laggedTreeNode.Lag + currentLag) + @"}^0 \left( ");
[5468]216      } else if (node.Symbol is VariableCondition) {
217        var conditionTreeNode = node as VariableConditionTreeNode;
[7038]218        string p = @"1 /  1 + \exp  - c_{" + constants.Count + "} ";
[5468]219        constants.Add(conditionTreeNode.Slope);
[7038]220        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"}   ";
[5468]221        constants.Add(conditionTreeNode.Threshold);
[7446]222        strBuilder.Append(@" \left( " + p + @"\cdot ");
[4327]223      } else {
224        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
225      }
226    }
227
[7140]228    private void FormatSep(ISymbolicExpressionTreeNode node, StringBuilder strBuilder, int step) {
[4327]229      if (node.Symbol is Addition) {
230        strBuilder.Append(" + ");
231      } else if (node.Symbol is Subtraction) {
232        strBuilder.Append(" - ");
233      } else if (node.Symbol is Multiplication) {
[5428]234        strBuilder.Append(@" \cdot ");
[4327]235      } else if (node.Symbol is Division) {
[7140]236        if (step + 1 == node.SubtreeCount)
237          strBuilder.Append(@"}{");
238        else
239          strBuilder.Append(@" }{ \cfrac{ ");
[4969]240      } else if (node.Symbol is Average) {
241        strBuilder.Append(@" + ");
242      } else if (node.Symbol is Logarithm) {
243        throw new InvalidOperationException();
244      } else if (node.Symbol is Exponential) {
245        throw new InvalidOperationException();
[7695]246      } else if (node.Symbol is Square) {
247        throw new InvalidOperationException();
248      } else if (node.Symbol is SquareRoot) {
249        throw new InvalidOperationException();
[4969]250      } else if (node.Symbol is Sine) {
251        throw new InvalidOperationException();
252      } else if (node.Symbol is Cosine) {
253        throw new InvalidOperationException();
254      } else if (node.Symbol is Tangent) {
255        throw new InvalidOperationException();
[7696]256      } else if (node.Symbol is AiryA) {
257        throw new InvalidOperationException();
258      } else if (node.Symbol is AiryB) {
259        throw new InvalidOperationException();
260      } else if (node.Symbol is Bessel) {
261        throw new InvalidOperationException();
262      } else if (node.Symbol is CosineIntegral) {
263        throw new InvalidOperationException();
264      } else if (node.Symbol is Dawson) {
265        throw new InvalidOperationException();
266      } else if (node.Symbol is Erf) {
267        throw new InvalidOperationException();
268      } else if (node.Symbol is ExponentialIntegralEi) {
269        throw new InvalidOperationException();
270      } else if (node.Symbol is FresnelCosineIntegral) {
271        throw new InvalidOperationException();
272      } else if (node.Symbol is FresnelSineIntegral) {
273        throw new InvalidOperationException();
274      } else if (node.Symbol is Gamma) {
275        throw new InvalidOperationException();
276      } else if (node.Symbol is HyperbolicCosineIntegral) {
277        throw new InvalidOperationException();
278      } else if (node.Symbol is HyperbolicSineIntegral) {
279        throw new InvalidOperationException();
[7697]280      } else if (node.Symbol is Norm) {
281        throw new InvalidOperationException();
[7696]282      } else if (node.Symbol is Psi) {
283        throw new InvalidOperationException();
284      } else if (node.Symbol is SineIntegral) {
285        throw new InvalidOperationException();
[4969]286      } else if (node.Symbol is GreaterThan) {
287        strBuilder.Append(@" > ");
288      } else if (node.Symbol is LessThan) {
289        strBuilder.Append(@" < ");
290      } else if (node.Symbol is And) {
[7446]291        strBuilder.Append(@" > 0  \right) \land \left(");
[4969]292      } else if (node.Symbol is Or) {
[7446]293        strBuilder.Append(@" > 0  \right) \lor \left(");
[4969]294      } else if (node.Symbol is Not) {
295        throw new InvalidOperationException();
296      } else if (node.Symbol is IfThenElse) {
[7446]297        strBuilder.Append(@" , ");
[4327]298      } else if (node.Symbol is ProgramRootSymbol) {
299        strBuilder.Append(@"\\" + Environment.NewLine);
300      } else if (node.Symbol is Defun) {
301      } else if (node.Symbol is InvokeFunction) {
302        strBuilder.Append(" , ");
303      } else if (node.Symbol is StartSymbol) {
[8798]304        strBuilder.Append(@"\\" + Environment.NewLine);
305        strBuilder.Append("target_" + (targetCount++) + "(t) & = ");
[5428]306      } else if (node.Symbol is Power) {
[7446]307        strBuilder.Append(@"\right) ^ { \operatorname{round} \left(");
[5428]308      } else if (node.Symbol is Root) {
[7446]309        strBuilder.Append(@"\right) ^ {  \cfrac{1}{ \operatorname{round} \left(");
[5468]310      } else if (node.Symbol is VariableCondition) {
311        var conditionTreeNode = node as VariableConditionTreeNode;
[7446]312        string p = @"1 / \left( 1 + \exp \left( - c_{" + constants.Count + "} ";
[5468]313        constants.Add(conditionTreeNode.Slope);
[7446]314        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"} \right) \right) \right)   ";
[5468]315        constants.Add(conditionTreeNode.Threshold);
[7446]316        strBuilder.Append(@" +  \left( 1 - " + p + @" \right) \cdot ");
[4327]317      } else {
318        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
319      }
320    }
321
[5745]322    private void FormatEnd(ISymbolicExpressionTreeNode node, StringBuilder strBuilder) {
[4327]323      if (node.Symbol is Addition) {
[7446]324        strBuilder.Append(@" \right) ");
[4327]325      } else if (node.Symbol is Subtraction) {
[7446]326        strBuilder.Append(@" \right) ");
[4327]327      } else if (node.Symbol is Multiplication) {
328      } else if (node.Symbol is Division) {
[7140]329        strBuilder.Append(" } ");
330        for (int i = 2; i < node.SubtreeCount; i++)
[5428]331          strBuilder.Append(" } ");
[4969]332      } else if (node.Symbol is Average) {
[7446]333        strBuilder.Append(@" \right) ");
[4969]334      } else if (node.Symbol is Logarithm) {
[7446]335        strBuilder.Append(@" \right) ");
[4969]336      } else if (node.Symbol is Exponential) {
[7446]337        strBuilder.Append(@" \right) ");
[7695]338      } else if (node.Symbol is Square) {
339        strBuilder.Append(@"\right)^2");
340      } else if (node.Symbol is SquareRoot) {
341        strBuilder.Append(@"}");
[4969]342      } else if (node.Symbol is Sine) {
[7446]343        strBuilder.Append(@" \right) ");
[4969]344      } else if (node.Symbol is Cosine) {
[7446]345        strBuilder.Append(@" \right) ");
[4969]346      } else if (node.Symbol is Tangent) {
[7446]347        strBuilder.Append(@" \right) ");
[7696]348      } else if (node.Symbol is AiryA) {
349        strBuilder.Append(@" \right) ");
350      } else if (node.Symbol is AiryB) {
351        strBuilder.Append(@" \right) ");
352      } else if (node.Symbol is Bessel) {
353        strBuilder.Append(@" \right) ");
354      } else if (node.Symbol is CosineIntegral) {
355        strBuilder.Append(@" \right) ");
356      } else if (node.Symbol is Dawson) {
357        strBuilder.Append(@" \right) ");
358      } else if (node.Symbol is Erf) {
359        strBuilder.Append(@" \right) ");
360      } else if (node.Symbol is ExponentialIntegralEi) {
361        strBuilder.Append(@" \right) ");
362      } else if (node.Symbol is FresnelCosineIntegral) {
363        strBuilder.Append(@" \right) ");
364      } else if (node.Symbol is FresnelSineIntegral) {
365        strBuilder.Append(@" \right) ");
366      } else if (node.Symbol is Gamma) {
367        strBuilder.Append(@" \right) ");
368      } else if (node.Symbol is HyperbolicCosineIntegral) {
369        strBuilder.Append(@" \right) ");
370      } else if (node.Symbol is HyperbolicSineIntegral) {
371        strBuilder.Append(@" \right) ");
[7697]372      } else if (node.Symbol is Norm) {
373        strBuilder.Append(@" \right) ");
[7696]374      } else if (node.Symbol is Psi) {
375        strBuilder.Append(@" \right) ");
376      } else if (node.Symbol is SineIntegral) {
377        strBuilder.Append(@" \right) ");
[4969]378      } else if (node.Symbol is GreaterThan) {
[7446]379        strBuilder.Append(@" \right) ");
[4969]380      } else if (node.Symbol is LessThan) {
[7446]381        strBuilder.Append(@" \right) ");
[4969]382      } else if (node.Symbol is And) {
[7446]383        strBuilder.Append(@" > 0 \right) \right) ");
[4969]384      } else if (node.Symbol is Or) {
[7446]385        strBuilder.Append(@" > 0 \right) \right) ");
[4969]386      } else if (node.Symbol is Not) {
[7446]387        strBuilder.Append(@" \right) ");
[4969]388      } else if (node.Symbol is IfThenElse) {
[7446]389        strBuilder.Append(@" \right) ");
[4327]390      } else if (node.Symbol is Constant) {
[5428]391      } else if (node.Symbol is LaggedVariable) {
[7038]392      } else if (node.Symbol is Variable) {
[4327]393      } else if (node.Symbol is ProgramRootSymbol) {
[7446]394        strBuilder
395          .AppendLine("\\end{align*}")
396          .AppendLine("\\begin{align*}")
397          .AppendLine("\\nonumber");
[4969]398        // output all constant values
399        if (constants.Count > 0) {
400          int i = 0;
401          foreach (var constant in constants) {
[7446]402            // replace "." with ".&" to align decimal points
403            var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant);
[7451]404            if (!constStr.Contains(".")) constStr = constStr + ".0";
[7446]405            constStr = constStr.Replace(".", "\\negthickspace&.");  // fix problem in rendering of aligned expressions
406            strBuilder.Append("c_{" + i + "}& = & " + constStr);
407            strBuilder.Append(@"\\");
[4969]408            i++;
409          }
410        }
[7446]411        strBuilder.AppendLine("\\end{align*}");
[4327]412      } else if (node.Symbol is Defun) {
413      } else if (node.Symbol is InvokeFunction) {
[7446]414        strBuilder.Append(@" \right) ");
[4327]415      } else if (node.Symbol is StartSymbol) {
416      } else if (node.Symbol is Argument) {
[5428]417      } else if (node.Symbol is Derivative) {
[7446]418        strBuilder.Append(@" \right) }{dt} ");
[5428]419      } else if (node.Symbol is TimeLag) {
420        var laggedNode = node as ILaggedTreeNode;
421        currentLag -= laggedNode.Lag;
422      } else if (node.Symbol is Power) {
[7446]423        strBuilder.Append(@" \right) } ");
[5428]424      } else if (node.Symbol is Root) {
[7446]425        strBuilder.Append(@" \right) } } ");
[5428]426      } else if (node.Symbol is Integral) {
[7446]427        strBuilder.Append(@" \right) ");
[5468]428      } else if (node.Symbol is VariableCondition) {
[7446]429        strBuilder.Append(@"\right) ");
[4327]430      } else {
431        throw new NotImplementedException("Export of " + node.Symbol + " is not implemented.");
432      }
433    }
[6975]434
[5428]435    private string LagToString(int lag) {
436      if (lag < 0) {
437        return "(t" + lag + ")";
438      } else if (lag > 0) {
439        return "(t+" + lag + ")";
[7038]440      } else return "";
[5428]441    }
[6975]442
443    private string EscapeLatexString(string s) {
[7446]444      return "\\text{" +
445        s
446         .Replace("\\", "\\\\")
447         .Replace("{", "\\{")
448         .Replace("}", "\\}")
449        + "}";
[6975]450    }
[4327]451  }
452}
Note: See TracBrowser for help on using the repository browser.