Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2522_RefactorPluginInfrastructure/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/SymbolicDataAnalysisExpressionTreeInterpreterTest.cs @ 15866

Last change on this file since 15866 was 13318, checked in by bburlacu, 9 years ago

#2442: Enabled power functions for the grammar in the TestCompiledInterpreterEstimatedValuesConsistency test method.

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