Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/SymbolicDataAnalysisExpressionTreeInterpreterTest.cs @ 18242

Last change on this file since 18242 was 17246, checked in by gkronber, 5 years ago

#2925: merged r17037:17242 from trunk to branch

File size: 30.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Globalization;
25using System.Linq;
26using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
27using HeuristicLab.Random;
28using Microsoft.VisualStudio.TestTools.UnitTesting;
29namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Tests {
30
31
32  [TestClass]
33  public class SymbolicDataAnalysisExpressionTreeInterpreterTest {
34    private const int N = 1000;
35    private const int Rows = 1000;
36    private const int Columns = 50;
37
38    private static Dataset ds = new Dataset(new string[] { "Y", "A", "B" }, new double[,] {
39        { 1.0, 1.0, 1.0 },
40        { 2.0, 2.0, 2.0 },
41        { 3.0, 1.0, 2.0 },
42        { 4.0, 1.0, 1.0 },
43        { 5.0, 2.0, 2.0 },
44        { 6.0, 1.0, 2.0 },
45        { 7.0, 1.0, 1.0 },
46        { 8.0, 2.0, 2.0 },
47        { 9.0, 1.0, 2.0 },
48        { 10.0, 1.0, 1.0 },
49        { 11.0, 2.0, 2.0 },
50        { 12.0, 1.0, 2.0 }
51      });
52
53    [TestMethod]
54    [TestCategory("Problems.DataAnalysis.Symbolic")]
55    [TestProperty("Time", "long")]
56    public void StandardInterpreterTestTypeCoherentGrammarPerformance() {
57      TestTypeCoherentGrammarPerformance(new SymbolicDataAnalysisExpressionTreeInterpreter(), 12.5e6);
58    }
59    [TestMethod]
60    [TestCategory("Problems.DataAnalysis.Symbolic")]
61    [TestProperty("Time", "long")]
62    public void StandardInterpreterTestFullGrammarPerformance() {
63      TestFullGrammarPerformance(new SymbolicDataAnalysisExpressionTreeInterpreter(), 12.5e6);
64    }
65    [TestMethod]
66    [TestCategory("Problems.DataAnalysis.Symbolic")]
67    [TestProperty("Time", "long")]
68    public void StandardInterpreterTestArithmeticGrammarPerformance() {
69      TestArithmeticGrammarPerformance(new SymbolicDataAnalysisExpressionTreeInterpreter(), 12.5e6);
70    }
71
72    [TestMethod]
73    [TestCategory("Problems.DataAnalysis.Symbolic")]
74    [TestProperty("Time", "long")]
75    public void CompiledInterpreterTestTypeCoherentGrammarPerformance() {
76      TestTypeCoherentGrammarPerformance(new SymbolicDataAnalysisExpressionCompiledTreeInterpreter(), 12.5e6);
77    }
78    [TestMethod]
79    [TestCategory("Problems.DataAnalysis.Symbolic")]
80    [TestProperty("Time", "long")]
81    public void CompiledInterpreterTestFullGrammarPerformance() {
82      TestFullGrammarPerformance(new SymbolicDataAnalysisExpressionCompiledTreeInterpreter(), 12.5e6);
83    }
84    [TestMethod]
85    [TestCategory("Problems.DataAnalysis.Symbolic")]
86    [TestProperty("Time", "long")]
87    public void CompiledInterpreterTestArithmeticGrammarPerformance() {
88      TestArithmeticGrammarPerformance(new SymbolicDataAnalysisExpressionCompiledTreeInterpreter(), 12.5e6);
89    }
90
91    [TestMethod]
92    [TestCategory("Problems.DataAnalysis.Symbolic")]
93    [TestProperty("Time", "long")]
94    public void ILEmittingInterpreterTestTypeCoherentGrammarPerformance() {
95      TestTypeCoherentGrammarPerformance(new SymbolicDataAnalysisExpressionTreeILEmittingInterpreter(), 7.5e6);
96    }
97    [TestMethod]
98    [TestCategory("Problems.DataAnalysis.Symbolic")]
99    [TestProperty("Time", "long")]
100    public void ILEmittingInterpreterTestArithmeticGrammarPerformance() {
101      TestArithmeticGrammarPerformance(new SymbolicDataAnalysisExpressionTreeILEmittingInterpreter(), 7.5e6);
102    }
103
104    [TestMethod]
105    [TestCategory("Problems.DataAnalysis.Symbolic")]
106    [TestProperty("Time", "long")]
107    public void LinearInterpreterTestTypeCoherentGrammarPerformance() {
108      TestTypeCoherentGrammarPerformance(new SymbolicDataAnalysisExpressionTreeLinearInterpreter(), 12.5e6);
109    }
110    [TestMethod]
111    [TestCategory("Problems.DataAnalysis.Symbolic")]
112    [TestProperty("Time", "long")]
113    public void LinearInterpreterTestFullGrammarPerformance() {
114      TestFullGrammarPerformance(new SymbolicDataAnalysisExpressionTreeLinearInterpreter(), 12.5e6);
115    }
116    [TestMethod]
117    [TestCategory("Problems.DataAnalysis.Symbolic")]
118    [TestProperty("Time", "long")]
119    public void LinearInterpreterTestArithmeticGrammarPerformance() {
120      TestArithmeticGrammarPerformance(new SymbolicDataAnalysisExpressionTreeLinearInterpreter(), 12.5e6);
121    }
122
123    [TestMethod]
124    [TestCategory("Problems.DataAnalysis.Symbolic")]
125    [TestProperty("Time", "long")]
126    public void BatchInterpreterTestTypeCoherentGrammarPerformance() {
127      TestTypeCoherentGrammarPerformance(new SymbolicDataAnalysisExpressionTreeBatchInterpreter(), 12.5e6);
128    }
129    [TestMethod]
130    [TestCategory("Problems.DataAnalysis.Symbolic")]
131    [TestProperty("Time", "long")]
132    public void BatchInterpreterTestArithmeticGrammarPerformance() {
133      TestArithmeticGrammarPerformance(new SymbolicDataAnalysisExpressionTreeBatchInterpreter(), 12.5e6);
134    }
135
136    private void TestTypeCoherentGrammarPerformance(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, double nodesPerSecThreshold) {
137      var twister = new MersenneTwister(31415);
138      var dataset = Util.CreateRandomDataset(twister, Rows, Columns);
139
140      var grammar = new TypeCoherentExpressionGrammar();
141      grammar.ConfigureAsDefaultRegressionGrammar();
142
143      var randomTrees = Util.CreateRandomTrees(twister, dataset, grammar, N, 1, 100, 0, 0);
144      foreach (ISymbolicExpressionTree tree in randomTrees) {
145        Util.InitTree(tree, twister, new List<string>(dataset.VariableNames));
146      }
147      double nodesPerSec = Util.CalculateEvaluatedNodesPerSec(randomTrees, interpreter, dataset, 3);
148      //mkommend: commented due to performance issues on the builder
149      // Assert.IsTrue(nodesPerSec > nodesPerSecThreshold); // evaluated nodes per seconds must be larger than 15mNodes/sec
150    }
151
152    private void TestFullGrammarPerformance(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, double nodesPerSecThreshold) {
153      var twister = new MersenneTwister(31415);
154      var dataset = Util.CreateRandomDataset(twister, Rows, Columns);
155
156      var grammar = new FullFunctionalExpressionGrammar();
157      var randomTrees = Util.CreateRandomTrees(twister, dataset, grammar, N, 1, 100, 0, 0);
158      foreach (ISymbolicExpressionTree tree in randomTrees) {
159        Util.InitTree(tree, twister, new List<string>(dataset.VariableNames));
160      }
161      double nodesPerSec = Util.CalculateEvaluatedNodesPerSec(randomTrees, interpreter, dataset, 3);
162      //mkommend: commented due to performance issues on the builder
163      //Assert.IsTrue(nodesPerSec > nodesPerSecThreshold); // evaluated nodes per seconds must be larger than 15mNodes/sec
164    }
165
166    private void TestArithmeticGrammarPerformance(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, double nodesPerSecThreshold) {
167      var twister = new MersenneTwister(31415);
168      var dataset = Util.CreateRandomDataset(twister, Rows, Columns);
169
170      var grammar = new ArithmeticExpressionGrammar();
171      var randomTrees = Util.CreateRandomTrees(twister, dataset, grammar, N, 1, 100, 0, 0);
172      foreach (SymbolicExpressionTree tree in randomTrees) {
173        Util.InitTree(tree, twister, new List<string>(dataset.VariableNames));
174      }
175
176      double nodesPerSec = Util.CalculateEvaluatedNodesPerSec(randomTrees, interpreter, dataset, 3);
177      //mkommend: commented due to performance issues on the builder
178      //Assert.IsTrue(nodesPerSec > nodesPerSecThreshold); // evaluated nodes per seconds must be larger than 15mNodes/sec
179    }
180
181
182    /// <summary>
183    ///A test for Evaluate
184    ///</summary>
185    [TestMethod]
186    [TestCategory("Problems.DataAnalysis.Symbolic")]
187    [TestProperty("Time", "short")]
188    public void StandardInterpreterTestEvaluation() {
189      var interpreter = new SymbolicDataAnalysisExpressionTreeInterpreter();
190      EvaluateTerminals(interpreter, ds);
191      EvaluateOperations(interpreter, ds);
192      EvaluateLaggedOperations(interpreter, ds);
193      EvaluateSpecialFunctions(interpreter, ds);
194      EvaluateAdf(interpreter, ds);
195    }
196
197    /// <summary>
198    ///A test for Evaluate
199    ///</summary>
200    [TestMethod]
201    [TestCategory("Problems.DataAnalysis.Symbolic")]
202    [TestProperty("Time", "short")]
203    public void ILEmittingInterpreterTestEvaluation() {
204      var interpreter = new SymbolicDataAnalysisExpressionTreeILEmittingInterpreter();
205      EvaluateTerminals(interpreter, ds);
206      EvaluateOperations(interpreter, ds);
207      EvaluateLaggedOperations(interpreter, ds);
208      EvaluateSpecialFunctions(interpreter, ds);
209    }
210
211    [TestMethod]
212    [TestCategory("Problems.DataAnalysis.Symbolic")]
213    [TestProperty("Time", "short")]
214    public void CompiledInterpreterTestEvaluation() {
215      var interpreter = new SymbolicDataAnalysisExpressionCompiledTreeInterpreter();
216      EvaluateTerminals(interpreter, ds);
217      EvaluateOperations(interpreter, ds);
218      EvaluateSpecialFunctions(interpreter, ds);
219    }
220
221    [TestMethod]
222    [TestCategory("Problems.DataAnalysis.Symbolic")]
223    [TestProperty("Time", "short")]
224    public void LinearInterpreterTestEvaluation() {
225      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
226      //ADFs are not supported by the linear interpreter
227      EvaluateTerminals(interpreter, ds);
228      EvaluateOperations(interpreter, ds);
229      EvaluateLaggedOperations(interpreter, ds);
230      EvaluateSpecialFunctions(interpreter, ds);
231    }
232
233    [TestMethod]
234    [TestCategory("Problems.DataAnalysis.Symbolic")]
235    [TestProperty("Time", "long")]
236    public void TestInterpretersEstimatedValuesConsistency() {
237      var twister = new MersenneTwister();
238      int seed = twister.Next(0, int.MaxValue);
239      twister.Seed((uint)seed);
240      const int numRows = 100;
241      var dataset = Util.CreateRandomDataset(twister, numRows, Columns);
242
243      var grammar = new TypeCoherentExpressionGrammar();
244
245      var interpreters = new ISymbolicDataAnalysisExpressionTreeInterpreter[] {
246        new SymbolicDataAnalysisExpressionTreeLinearInterpreter(),
247        new SymbolicDataAnalysisExpressionTreeInterpreter(),
248      };
249
250      var rows = Enumerable.Range(0, numRows).ToList();
251      var randomTrees = Util.CreateRandomTrees(twister, dataset, grammar, N, 1, 10, 0, 0);
252      foreach (ISymbolicExpressionTree tree in randomTrees) {
253        Util.InitTree(tree, twister, new List<string>(dataset.VariableNames));
254      }
255
256      for (int i = 0; i < randomTrees.Length; ++i) {
257        var tree = randomTrees[i];
258        var valuesMatrix = interpreters.Select(x => x.GetSymbolicExpressionTreeValues(tree, dataset, rows)).ToList();
259        for (int m = 0; m < interpreters.Length - 1; ++m) {
260          var sum = valuesMatrix[m].Sum();
261          for (int n = m + 1; n < interpreters.Length; ++n) {
262            var s = valuesMatrix[n].Sum();
263            if (double.IsNaN(sum) && double.IsNaN(s)) continue;
264
265            string errorMessage = string.Format("Interpreters {0} and {1} do not agree on tree {2} (seed = {3}).", interpreters[m].Name, interpreters[n].Name, i, seed);
266            Assert.AreEqual(sum, s, 1e-12, errorMessage);
267          }
268        }
269      }
270    }
271
272    [TestMethod]
273    [TestCategory("Problems.DataAnalysis.Symbolic")]
274    [TestProperty("Time", "long")]
275    public void TestCompiledInterpreterEstimatedValuesConsistency() {
276      const double delta = 1e-12;
277
278      var twister = new MersenneTwister();
279      int seed = twister.Next(0, int.MaxValue);
280      twister.Seed((uint)seed);
281
282      Console.WriteLine(seed);
283
284      const int numRows = 100;
285      var dataset = Util.CreateRandomDataset(twister, numRows, Columns);
286
287      var grammar = new TypeCoherentExpressionGrammar();
288      grammar.ConfigureAsDefaultRegressionGrammar();
289      grammar.Symbols.First(x => x.Name == "Power Functions").Enabled = true;
290
291      var randomTrees = Util.CreateRandomTrees(twister, dataset, grammar, N, 1, 10, 0, 0);
292      foreach (ISymbolicExpressionTree tree in randomTrees) {
293        Util.InitTree(tree, twister, new List<string>(dataset.VariableNames));
294      }
295
296      var interpreters = new ISymbolicDataAnalysisExpressionTreeInterpreter[] {
297        new SymbolicDataAnalysisExpressionCompiledTreeInterpreter(),
298        new SymbolicDataAnalysisExpressionTreeInterpreter(),
299        new SymbolicDataAnalysisExpressionTreeLinearInterpreter(),
300      };
301      var rows = Enumerable.Range(0, numRows).ToList();
302      var formatter = new SymbolicExpressionTreeHierarchicalFormatter();
303
304      for (int i = 0; i < randomTrees.Length; ++i) {
305        var tree = randomTrees[i];
306        var valuesMatrix = interpreters.Select(x => x.GetSymbolicExpressionTreeValues(tree, dataset, rows).ToList()).ToList();
307        for (int m = 0; m < interpreters.Length - 1; ++m) {
308          for (int n = m + 1; n < interpreters.Length; ++n) {
309            for (int row = 0; row < numRows; ++row) {
310              var v1 = valuesMatrix[m][row];
311              var v2 = valuesMatrix[n][row];
312              if (double.IsNaN(v1) && double.IsNaN(v2)) continue;
313              if (Math.Abs(v1 - v2) > delta) {
314                Console.WriteLine(formatter.Format(tree));
315                foreach (var node in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix().ToList()) {
316                  var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
317                  if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(twister);
318                  rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
319
320                  var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
321                  if (startNode.HasLocalParameters) startNode.ResetLocalParameters(twister);
322                  startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
323
324                  rootNode.AddSubtree(startNode);
325                  var t = new SymbolicExpressionTree(rootNode);
326                  var start = t.Root.GetSubtree(0);
327                  var p = node.Parent;
328                  start.AddSubtree(node);
329                  Console.WriteLine(node);
330
331                  var y1 = interpreters[m].GetSymbolicExpressionTreeValues(t, dataset, new[] { row }).First();
332                  var y2 = interpreters[n].GetSymbolicExpressionTreeValues(t, dataset, new[] { row }).First();
333
334                  if (double.IsNaN(y1) && double.IsNaN(y2)) continue;
335                  string prefix = Math.Abs(y1 - y2) > delta ? "++" : "==";
336                  Console.WriteLine("\t{0} Row {1}: {2} {3}, Deviation = {4}", prefix, row, y1, y2, Math.Abs(y1 - y2));
337                  node.Parent = p;
338                }
339              }
340              string errorMessage = string.Format("Interpreters {0} and {1} do not agree on tree {2} and row {3} (seed = {4}).", interpreters[m].Name, interpreters[n].Name, i, row, seed);
341              Assert.AreEqual(v1, v2, delta, errorMessage);
342            }
343          }
344        }
345      }
346    }
347
348    private void EvaluateTerminals(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
349      // constants
350      Evaluate(interpreter, ds, "(+ 1.5 3.5)", 0, 5.0);
351
352      // variables
353      Evaluate(interpreter, ds, "(variable 2.0 a)", 0, 2.0);
354      Evaluate(interpreter, ds, "(variable 2.0 a)", 1, 4.0);
355    }
356
357    private void EvaluateAdf(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
358
359      // ADF     
360      Evaluate(interpreter, ds, @"(PROG
361                                    (MAIN
362                                      (CALL ADF0))
363                                    (defun ADF0 1.0))", 1, 1.0);
364      Evaluate(interpreter, ds, @"(PROG
365                                    (MAIN
366                                      (* (CALL ADF0) (CALL ADF0)))
367                                    (defun ADF0 2.0))", 1, 4.0);
368      Evaluate(interpreter, ds, @"(PROG
369                                    (MAIN
370                                      (CALL ADF0 2.0 3.0))
371                                    (defun ADF0
372                                      (+ (ARG 0) (ARG 1))))", 1, 5.0);
373      Evaluate(interpreter, ds, @"(PROG
374                                    (MAIN (CALL ADF1 2.0 3.0))
375                                    (defun ADF0
376                                      (- (ARG 1) (ARG 0)))
377                                    (defun ADF1
378                                      (+ (CALL ADF0 (ARG 1) (ARG 0))
379                                         (CALL ADF0 (ARG 0) (ARG 1)))))", 1, 0.0);
380      Evaluate(interpreter, ds, @"(PROG
381                                    (MAIN (CALL ADF1 (variable 2.0 a) 3.0))
382                                    (defun ADF0
383                                      (- (ARG 1) (ARG 0)))
384                                    (defun ADF1                                                                             
385                                      (CALL ADF0 (ARG 1) (ARG 0))))", 1, 1.0);
386      Evaluate(interpreter, ds,
387               @"(PROG
388                                    (MAIN (CALL ADF1 (variable 2.0 a) 3.0))
389                                    (defun ADF0
390                                      (- (ARG 1) (ARG 0)))
391                                    (defun ADF1                                                                             
392                                      (+ (CALL ADF0 (ARG 1) (ARG 0))
393                                         (CALL ADF0 (ARG 0) (ARG 1)))))", 1, 0.0);
394    }
395
396    private void EvaluateSpecialFunctions(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
397      // special functions
398      Action<double> checkAiry = (x) => {
399        double ai, aip, bi, bip;
400        alglib.airy(x, out ai, out aip, out bi, out bip);
401        Evaluate(interpreter, ds, "(airya " + x + ")", 0, ai);
402        Evaluate(interpreter, ds, "(airyb " + x + ")", 0, bi);
403      };
404
405      Action<double> checkBessel = (x) => {
406        Evaluate(interpreter, ds, "(bessel " + x + ")", 0, alglib.besseli0(x));
407      };
408
409      Action<double> checkSinCosIntegrals = (x) => {
410        double si, ci;
411        alglib.sinecosineintegrals(x, out si, out ci);
412        Evaluate(interpreter, ds, "(cosint " + x + ")", 0, ci);
413        Evaluate(interpreter, ds, "(sinint " + x + ")", 0, si);
414      };
415      Action<double> checkHypSinCosIntegrals = (x) => {
416        double shi, chi;
417        alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
418        Evaluate(interpreter, ds, "(hypcosint " + x + ")", 0, chi);
419        Evaluate(interpreter, ds, "(hypsinint " + x + ")", 0, shi);
420      };
421      Action<double> checkFresnelSinCosIntegrals = (x) => {
422        double c = 0, s = 0;
423        alglib.fresnelintegral(x, ref c, ref s);
424        Evaluate(interpreter, ds, "(fresnelcosint " + x + ")", 0, c);
425        Evaluate(interpreter, ds, "(fresnelsinint " + x + ")", 0, s);
426      };
427      Action<double> checkNormErf = (x) => {
428        Evaluate(interpreter, ds, "(norm " + x + ")", 0, alglib.normaldistribution(x));
429        Evaluate(interpreter, ds, "(erf " + x + ")", 0, alglib.errorfunction(x));
430      };
431
432      Action<double> checkGamma = (x) => {
433        Evaluate(interpreter, ds, "(gamma " + x + ")", 0, alglib.gammafunction(x));
434      };
435      Action<double> checkPsi = (x) => {
436        try {
437          Evaluate(interpreter, ds, "(psi " + x + ")", 0, alglib.psi(x));
438        } catch (alglib.alglibexception) { // ignore cases where alglib throws an exception
439        }
440      };
441      Action<double> checkDawson = (x) => {
442        Evaluate(interpreter, ds, "(dawson " + x + ")", 0, alglib.dawsonintegral(x));
443      };
444      Action<double> checkExpInt = (x) => {
445        Evaluate(interpreter, ds, "(expint " + x + ")", 0, alglib.exponentialintegralei(x));
446      };
447
448      foreach (var e in new[] { -2.0, -1.0, 0.0, 1.0, 2.0 }) {
449        checkAiry(e);
450        checkBessel(e);
451        checkSinCosIntegrals(e);
452        checkGamma(e);
453        checkExpInt(e);
454        checkDawson(e);
455        checkPsi(e);
456        checkNormErf(e);
457        checkFresnelSinCosIntegrals(e);
458        checkHypSinCosIntegrals(e);
459      }
460    }
461
462    private void EvaluateLaggedOperations(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
463      // lag
464      Evaluate(interpreter, ds, "(lagVariable 1.0 a -1) ", 1, ds.GetDoubleValue("A", 0));
465      Evaluate(interpreter, ds, "(lagVariable 1.0 a -1) ", 2, ds.GetDoubleValue("A", 1));
466      Evaluate(interpreter, ds, "(lagVariable 1.0 a 0) ", 2, ds.GetDoubleValue("A", 2));
467      Evaluate(interpreter, ds, "(lagVariable 1.0 a 1) ", 0, ds.GetDoubleValue("A", 1));
468
469      // integral
470      Evaluate(interpreter, ds, "(integral -1.0 (variable 1.0 a)) ", 1, ds.GetDoubleValue("A", 0) + ds.GetDoubleValue("A", 1));
471      Evaluate(interpreter, ds, "(integral -1.0 (lagVariable 1.0 a 1)) ", 1, ds.GetDoubleValue("A", 1) + ds.GetDoubleValue("A", 2));
472      Evaluate(interpreter, ds, "(integral -2.0 (variable 1.0 a)) ", 2, ds.GetDoubleValue("A", 0) + ds.GetDoubleValue("A", 1) + ds.GetDoubleValue("A", 2));
473      Evaluate(interpreter, ds, "(integral -1.0 (* (variable 1.0 a) (variable 1.0 b)))", 1, ds.GetDoubleValue("A", 0) * ds.GetDoubleValue("B", 0) + ds.GetDoubleValue("A", 1) * ds.GetDoubleValue("B", 1));
474      Evaluate(interpreter, ds, "(integral -2.0 3.0)", 1, 9.0);
475
476      // derivative
477      // (f_0 + 2 * f_1 - 2 * f_3 - f_4) / 8; // h = 1
478      Evaluate(interpreter, ds, "(diff (variable 1.0 a)) ", 5, (ds.GetDoubleValue("A", 5) + 2 * ds.GetDoubleValue("A", 4) - 2 * ds.GetDoubleValue("A", 2) - ds.GetDoubleValue("A", 1)) / 8.0);
479      Evaluate(interpreter, ds, "(diff (variable 1.0 b)) ", 5, (ds.GetDoubleValue("B", 5) + 2 * ds.GetDoubleValue("B", 4) - 2 * ds.GetDoubleValue("B", 2) - ds.GetDoubleValue("B", 1)) / 8.0);
480      Evaluate(interpreter, ds, "(diff (* (variable 1.0 a) (variable 1.0 b)))", 5, +
481        (ds.GetDoubleValue("A", 5) * ds.GetDoubleValue("B", 5) +
482        2 * ds.GetDoubleValue("A", 4) * ds.GetDoubleValue("B", 4) -
483        2 * ds.GetDoubleValue("A", 2) * ds.GetDoubleValue("B", 2) -
484        ds.GetDoubleValue("A", 1) * ds.GetDoubleValue("B", 1)) / 8.0);
485      Evaluate(interpreter, ds, "(diff -2.0 3.0)", 5, 0.0);
486
487      // timelag
488      Evaluate(interpreter, ds, "(lag -1.0 (lagVariable 1.0 a 2)) ", 1, ds.GetDoubleValue("A", 2));
489      Evaluate(interpreter, ds, "(lag -2.0 (lagVariable 1.0 a 2)) ", 2, ds.GetDoubleValue("A", 2));
490      Evaluate(interpreter, ds, "(lag -1.0 (* (lagVariable 1.0 a 1) (lagVariable 1.0 b 2)))", 1, ds.GetDoubleValue("A", 1) * ds.GetDoubleValue("B", 2));
491      Evaluate(interpreter, ds, "(lag -2.0 3.0)", 1, 3.0);
492    }
493
494    private void EvaluateOperations(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
495      // addition
496      Evaluate(interpreter, ds, "(+ (variable 2.0 a ))", 1, 4.0);
497      Evaluate(interpreter, ds, "(+ (variable 2.0 a ) (variable 3.0 b ))", 0, 5.0);
498      Evaluate(interpreter, ds, "(+ (variable 2.0 a ) (variable 3.0 b ))", 1, 10.0);
499      Evaluate(interpreter, ds, "(+ (variable 2.0 a) (variable 3.0 b ))", 2, 8.0);
500      Evaluate(interpreter, ds, "(+ 8.0 2.0 2.0)", 0, 12.0);
501
502      // subtraction
503      Evaluate(interpreter, ds, "(- (variable 2.0 a ))", 1, -4.0);
504      Evaluate(interpreter, ds, "(- (variable 2.0 a ) (variable 3.0 b))", 0, -1.0);
505      Evaluate(interpreter, ds, "(- (variable 2.0 a ) (variable 3.0 b ))", 1, -2.0);
506      Evaluate(interpreter, ds, "(- (variable 2.0 a ) (variable 3.0 b ))", 2, -4.0);
507      Evaluate(interpreter, ds, "(- 8.0 2.0 2.0)", 0, 4.0);
508
509      // multiplication
510      Evaluate(interpreter, ds, "(* (variable 2.0 a ))", 0, 2.0);
511      Evaluate(interpreter, ds, "(* (variable 2.0 a ) (variable 3.0 b ))", 0, 6.0);
512      Evaluate(interpreter, ds, "(* (variable 2.0 a ) (variable 3.0 b ))", 1, 24.0);
513      Evaluate(interpreter, ds, "(* (variable 2.0 a ) (variable 3.0 b ))", 2, 12.0);
514      Evaluate(interpreter, ds, "(* 8.0 2.0 2.0)", 0, 32.0);
515
516      // division
517      Evaluate(interpreter, ds, "(/ (variable 2.0 a ))", 1, 1.0 / 4.0);
518      Evaluate(interpreter, ds, "(/ (variable 2.0 a ) 2.0)", 0, 1.0);
519      Evaluate(interpreter, ds, "(/ (variable 2.0 a ) 2.0)", 1, 2.0);
520      Evaluate(interpreter, ds, "(/ (variable 3.0 b ) 2.0)", 2, 3.0);
521      Evaluate(interpreter, ds, "(/ 8.0 2.0 2.0)", 0, 2.0);
522
523      // gt
524      Evaluate(interpreter, ds, "(> (variable 2.0 a) 2.0)", 0, -1.0);
525      Evaluate(interpreter, ds, "(> 2.0 (variable 2.0 a))", 0, -1.0);
526      Evaluate(interpreter, ds, "(> (variable 2.0 a) 1.9)", 0, 1.0);
527      Evaluate(interpreter, ds, "(> 1.9 (variable 2.0 a))", 0, -1.0);
528      Evaluate(interpreter, ds, "(> (log -1.0) (log -1.0))", 0, -1.0); // (> nan nan) should be false
529
530      // lt
531      Evaluate(interpreter, ds, "(< (variable 2.0 a) 2.0)", 0, -1.0);
532      Evaluate(interpreter, ds, "(< 2.0 (variable 2.0 a))", 0, -1.0);
533      Evaluate(interpreter, ds, "(< (variable 2.0 a) 1.9)", 0, -1.0);
534      Evaluate(interpreter, ds, "(< 1.9 (variable 2.0 a))", 0, 1.0);
535      Evaluate(interpreter, ds, "(< (log -1.0) (log -1.0))", 0, -1.0); // (< nan nan) should be false
536
537      // If
538      Evaluate(interpreter, ds, "(if -10.0 2.0 3.0)", 0, 3.0);
539      Evaluate(interpreter, ds, "(if -1.0 2.0 3.0)", 0, 3.0);
540      Evaluate(interpreter, ds, "(if 0.0 2.0 3.0)", 0, 3.0);
541      Evaluate(interpreter, ds, "(if 1.0 2.0 3.0)", 0, 2.0);
542      Evaluate(interpreter, ds, "(if 10.0 2.0 3.0)", 0, 2.0);
543      Evaluate(interpreter, ds, "(if (log -1.0) 2.0 3.0)", 0, 3.0); // if(nan) should return the else branch
544
545      // NOT
546      Evaluate(interpreter, ds, "(not -1.0)", 0, 1.0);
547      Evaluate(interpreter, ds, "(not -2.0)", 0, 1.0);
548      Evaluate(interpreter, ds, "(not 1.0)", 0, -1.0);
549      Evaluate(interpreter, ds, "(not 2.0)", 0, -1.0);
550      Evaluate(interpreter, ds, "(not 0.0)", 0, 1.0);
551      Evaluate(interpreter, ds, "(not (log -1.0))", 0, 1.0);
552
553      // AND
554      Evaluate(interpreter, ds, "(and -1.0 -2.0)", 0, -1.0);
555      Evaluate(interpreter, ds, "(and -1.0 2.0)", 0, -1.0);
556      Evaluate(interpreter, ds, "(and 1.0 -2.0)", 0, -1.0);
557      Evaluate(interpreter, ds, "(and 1.0 0.0)", 0, -1.0);
558      Evaluate(interpreter, ds, "(and 0.0 0.0)", 0, -1.0);
559      Evaluate(interpreter, ds, "(and 1.0 2.0)", 0, 1.0);
560      Evaluate(interpreter, ds, "(and 1.0 2.0 3.0)", 0, 1.0);
561      Evaluate(interpreter, ds, "(and 1.0 -2.0 3.0)", 0, -1.0);
562      Evaluate(interpreter, ds, "(and (log -1.0))", 0, -1.0); // (and NaN)
563      Evaluate(interpreter, ds, "(and (log -1.0)  1.0)", 0, -1.0); // (and NaN 1.0)
564
565      // OR
566      Evaluate(interpreter, ds, "(or -1.0 -2.0)", 0, -1.0);
567      Evaluate(interpreter, ds, "(or -1.0 2.0)", 0, 1.0);
568      Evaluate(interpreter, ds, "(or 1.0 -2.0)", 0, 1.0);
569      Evaluate(interpreter, ds, "(or 1.0 2.0)", 0, 1.0);
570      Evaluate(interpreter, ds, "(or 0.0 0.0)", 0, -1.0);
571      Evaluate(interpreter, ds, "(or -1.0 -2.0 -3.0)", 0, -1.0);
572      Evaluate(interpreter, ds, "(or -1.0 -2.0 3.0)", 0, 1.0);
573      Evaluate(interpreter, ds, "(or (log -1.0))", 0, -1.0); // (or NaN)
574      Evaluate(interpreter, ds, "(or (log -1.0)  1.0)", 0, -1.0); // (or NaN 1.0)
575
576      // XOR
577      Evaluate(interpreter, ds, "(xor -1.0 -2.0)", 0, -1.0);
578      Evaluate(interpreter, ds, "(xor -1.0 2.0)", 0, 1.0);
579      Evaluate(interpreter, ds, "(xor 1.0 -2.0)", 0, 1.0);
580      Evaluate(interpreter, ds, "(xor 1.0 2.0)", 0, -1.0);
581      Evaluate(interpreter, ds, "(xor 0.0 0.0)", 0, -1.0);
582      Evaluate(interpreter, ds, "(xor -1.0 -2.0 -3.0)", 0, -1.0);
583      Evaluate(interpreter, ds, "(xor -1.0 -2.0 3.0)", 0, 1.0);
584      Evaluate(interpreter, ds, "(xor -1.0 2.0 3.0)", 0, -1.0);
585      Evaluate(interpreter, ds, "(xor 1.0 2.0 3.0)", 0, 1.0);
586      Evaluate(interpreter, ds, "(xor (log -1.0))", 0, -1.0);
587      Evaluate(interpreter, ds, "(xor (log -1.0)  1.0)", 0, 1.0);
588
589      // sin, cos, tan
590      Evaluate(interpreter, ds, "(sin " + Math.PI.ToString(NumberFormatInfo.InvariantInfo) + ")", 0, 0.0);
591      Evaluate(interpreter, ds, "(sin 0.0)", 0, 0.0);
592      Evaluate(interpreter, ds, "(cos " + Math.PI.ToString(NumberFormatInfo.InvariantInfo) + ")", 0, -1.0);
593      Evaluate(interpreter, ds, "(cos 0.0)", 0, 1.0);
594      Evaluate(interpreter, ds, "(tan " + Math.PI.ToString(NumberFormatInfo.InvariantInfo) + ")", 0, Math.Tan(Math.PI));
595      Evaluate(interpreter, ds, "(tan 0.0)", 0, Math.Tan(Math.PI));
596
597      // exp, log
598      Evaluate(interpreter, ds, "(log (exp 7.0))", 0, Math.Log(Math.Exp(7)));
599      Evaluate(interpreter, ds, "(exp (log 7.0))", 0, Math.Exp(Math.Log(7)));
600      Evaluate(interpreter, ds, "(log -3.0)", 0, Math.Log(-3));
601
602      // power
603      Evaluate(interpreter, ds, "(pow 2.0 3.0)", 0, 8.0);
604      Evaluate(interpreter, ds, "(pow 4.0 0.5)", 0, 1.0); // interpreter should round to the nearest integer value value (.5 is rounded to the even number)
605      Evaluate(interpreter, ds, "(pow 4.0 2.5)", 0, 16.0); // interpreter should round to the nearest integer value value (.5 is rounded to the even number)
606      Evaluate(interpreter, ds, "(pow -2.0 3.0)", 0, -8.0);
607      Evaluate(interpreter, ds, "(pow 2.0 -3.0)", 0, 1.0 / 8.0);
608      Evaluate(interpreter, ds, "(pow -2.0 -3.0)", 0, -1.0 / 8.0);
609
610      // root
611      Evaluate(interpreter, ds, "(root 9.0 2.0)", 0, 3.0);
612      Evaluate(interpreter, ds, "(root 27.0 3.0)", 0, 3.0);
613      Evaluate(interpreter, ds, "(root 2.0 -3.0)", 0, Math.Pow(2.0, -1.0 / 3.0));
614
615      // mean
616      Evaluate(interpreter, ds, "(mean -1.0 1.0 -1.0)", 0, -1.0 / 3.0);
617    }
618
619    private void Evaluate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds, string expr, int index, double expected) {
620      var importer = new SymbolicExpressionImporter();
621      ISymbolicExpressionTree tree = importer.Import(expr);
622
623      double actual = interpreter.GetSymbolicExpressionTreeValues(tree, ds, Enumerable.Range(index, 1)).First();
624
625      Assert.IsFalse(double.IsNaN(actual) && !double.IsNaN(expected));
626      Assert.IsFalse(!double.IsNaN(actual) && double.IsNaN(expected));
627      if (!double.IsNaN(actual) && !double.IsNaN(expected))
628        Assert.AreEqual(expected, actual, 1.0E-12, expr);
629    }
630  }
631}
Note: See TracBrowser for help on using the repository browser.