Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/SymbolicDataAnalysisExpressionTreeInterpreterTest.cs

Last change on this file was 18087, checked in by mkommend, 3 years ago

#2521: Merged latest trunk changes part II.

File size: 31.3 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-8;
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      grammar.Symbols.First(x => x is Cube).Enabled = true;
291      grammar.Symbols.First(x => x is CubeRoot).Enabled = true;
292      grammar.Symbols.First(x => x is Square).Enabled = true;
293      grammar.Symbols.First(x => x is SquareRoot).Enabled = true;
294      grammar.Symbols.First(x => x is Absolute).Enabled = true;
295      grammar.Symbols.First(x => x is Sine).Enabled = true;
296      grammar.Symbols.First(x => x is Cosine).Enabled = true;
297      grammar.Symbols.First(x => x is Tangent).Enabled = true;
298      grammar.Symbols.First(x => x is Root).Enabled = false;
299      grammar.Symbols.First(x => x is Power).Enabled = false;
300
301      var randomTrees = Util.CreateRandomTrees(twister, dataset, grammar, N, 1, 10, 0, 0);
302      foreach (ISymbolicExpressionTree tree in randomTrees) {
303        Util.InitTree(tree, twister, new List<string>(dataset.VariableNames));
304      }
305
306      var interpreters = new ISymbolicDataAnalysisExpressionTreeInterpreter[] {
307        new SymbolicDataAnalysisExpressionCompiledTreeInterpreter(),
308        new SymbolicDataAnalysisExpressionTreeInterpreter(),
309        new SymbolicDataAnalysisExpressionTreeLinearInterpreter(),
310      };
311      var rows = Enumerable.Range(0, numRows).ToList();
312      var formatter = new SymbolicExpressionTreeHierarchicalFormatter();
313
314      for (int i = 0; i < randomTrees.Length; ++i) {
315        var tree = randomTrees[i];
316        var valuesMatrix = interpreters.Select(x => x.GetSymbolicExpressionTreeValues(tree, dataset, rows).ToList()).ToList();
317        for (int m = 0; m < interpreters.Length - 1; ++m) {
318          for (int n = m + 1; n < interpreters.Length; ++n) {
319            for (int row = 0; row < numRows; ++row) {
320              var v1 = valuesMatrix[m][row];
321              var v2 = valuesMatrix[n][row];
322              if (double.IsNaN(v1) && double.IsNaN(v2)) continue;
323              if (v1 != v2 && Math.Abs(1.0 - v1 / v2) >= delta) {
324                Console.WriteLine(formatter.Format(tree));
325                foreach (var node in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix().ToList()) {
326                  var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
327                  if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(twister);
328                  rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
329
330                  var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
331                  if (startNode.HasLocalParameters) startNode.ResetLocalParameters(twister);
332                  startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
333
334                  rootNode.AddSubtree(startNode);
335                  var t = new SymbolicExpressionTree(rootNode);
336                  var start = t.Root.GetSubtree(0);
337                  var p = node.Parent;
338                  start.AddSubtree(node);
339                  Console.WriteLine(node);
340
341                  var y1 = interpreters[m].GetSymbolicExpressionTreeValues(t, dataset, new[] { row }).First();
342                  var y2 = interpreters[n].GetSymbolicExpressionTreeValues(t, dataset, new[] { row }).First();
343
344                  if (double.IsNaN(y1) && double.IsNaN(y2)) continue;
345                  string prefix = Math.Abs(y1 - y2) > delta ? "++" : "==";
346                  Console.WriteLine("\t{0} Row {1}: {2} {3}, Deviation = {4}", prefix, row, y1, y2, Math.Abs(y1 - y2));
347                  node.Parent = p;
348                }
349              }
350              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);
351              Assert.IsTrue(double.IsNaN(v1) && double.IsNaN(v2) ||
352                            v1 == v2 || // in particular 0 = 0
353                            Math.Abs(1.0 - v1 / v2) < delta, errorMessage);
354            }
355          }
356        }
357      }
358    }
359
360    private void EvaluateTerminals(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
361      // constants
362      Evaluate(interpreter, ds, "(+ 1.5 3.5)", 0, 5.0);
363
364      // variables
365      Evaluate(interpreter, ds, "(variable 2.0 a)", 0, 2.0);
366      Evaluate(interpreter, ds, "(variable 2.0 a)", 1, 4.0);
367    }
368
369    private void EvaluateAdf(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
370
371      // ADF     
372      Evaluate(interpreter, ds, @"(PROG
373                                    (MAIN
374                                      (CALL ADF0))
375                                    (defun ADF0 1.0))", 1, 1.0);
376      Evaluate(interpreter, ds, @"(PROG
377                                    (MAIN
378                                      (* (CALL ADF0) (CALL ADF0)))
379                                    (defun ADF0 2.0))", 1, 4.0);
380      Evaluate(interpreter, ds, @"(PROG
381                                    (MAIN
382                                      (CALL ADF0 2.0 3.0))
383                                    (defun ADF0
384                                      (+ (ARG 0) (ARG 1))))", 1, 5.0);
385      Evaluate(interpreter, ds, @"(PROG
386                                    (MAIN (CALL ADF1 2.0 3.0))
387                                    (defun ADF0
388                                      (- (ARG 1) (ARG 0)))
389                                    (defun ADF1
390                                      (+ (CALL ADF0 (ARG 1) (ARG 0))
391                                         (CALL ADF0 (ARG 0) (ARG 1)))))", 1, 0.0);
392      Evaluate(interpreter, ds, @"(PROG
393                                    (MAIN (CALL ADF1 (variable 2.0 a) 3.0))
394                                    (defun ADF0
395                                      (- (ARG 1) (ARG 0)))
396                                    (defun ADF1                                                                             
397                                      (CALL ADF0 (ARG 1) (ARG 0))))", 1, 1.0);
398      Evaluate(interpreter, ds,
399               @"(PROG
400                                    (MAIN (CALL ADF1 (variable 2.0 a) 3.0))
401                                    (defun ADF0
402                                      (- (ARG 1) (ARG 0)))
403                                    (defun ADF1                                                                             
404                                      (+ (CALL ADF0 (ARG 1) (ARG 0))
405                                         (CALL ADF0 (ARG 0) (ARG 1)))))", 1, 0.0);
406    }
407
408    private void EvaluateSpecialFunctions(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
409      // special functions
410      Action<double> checkAiry = (x) => {
411        double ai, aip, bi, bip;
412        alglib.airy(x, out ai, out aip, out bi, out bip);
413        Evaluate(interpreter, ds, "(airya " + x + ")", 0, ai);
414        Evaluate(interpreter, ds, "(airyb " + x + ")", 0, bi);
415      };
416
417      Action<double> checkBessel = (x) => {
418        Evaluate(interpreter, ds, "(bessel " + x + ")", 0, alglib.besseli0(x));
419      };
420
421      Action<double> checkSinCosIntegrals = (x) => {
422        double si, ci;
423        alglib.sinecosineintegrals(x, out si, out ci);
424        Evaluate(interpreter, ds, "(cosint " + x + ")", 0, ci);
425        Evaluate(interpreter, ds, "(sinint " + x + ")", 0, si);
426      };
427      Action<double> checkHypSinCosIntegrals = (x) => {
428        double shi, chi;
429        alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
430        Evaluate(interpreter, ds, "(hypcosint " + x + ")", 0, chi);
431        Evaluate(interpreter, ds, "(hypsinint " + x + ")", 0, shi);
432      };
433      Action<double> checkFresnelSinCosIntegrals = (x) => {
434        double c = 0, s = 0;
435        alglib.fresnelintegral(x, ref c, ref s);
436        Evaluate(interpreter, ds, "(fresnelcosint " + x + ")", 0, c);
437        Evaluate(interpreter, ds, "(fresnelsinint " + x + ")", 0, s);
438      };
439      Action<double> checkNormErf = (x) => {
440        Evaluate(interpreter, ds, "(norm " + x + ")", 0, alglib.normaldistribution(x));
441        Evaluate(interpreter, ds, "(erf " + x + ")", 0, alglib.errorfunction(x));
442      };
443
444      Action<double> checkGamma = (x) => {
445        Evaluate(interpreter, ds, "(gamma " + x + ")", 0, alglib.gammafunction(x));
446      };
447      Action<double> checkPsi = (x) => {
448        try {
449          Evaluate(interpreter, ds, "(psi " + x + ")", 0, alglib.psi(x));
450        } catch (alglib.alglibexception) { // ignore cases where alglib throws an exception
451        }
452      };
453      Action<double> checkDawson = (x) => {
454        Evaluate(interpreter, ds, "(dawson " + x + ")", 0, alglib.dawsonintegral(x));
455      };
456      Action<double> checkExpInt = (x) => {
457        Evaluate(interpreter, ds, "(expint " + x + ")", 0, alglib.exponentialintegralei(x));
458      };
459
460      foreach (var e in new[] { -2.0, -1.0, 0.0, 1.0, 2.0 }) {
461        checkAiry(e);
462        checkBessel(e);
463        checkSinCosIntegrals(e);
464        checkGamma(e);
465        checkExpInt(e);
466        checkDawson(e);
467        checkPsi(e);
468        checkNormErf(e);
469        checkFresnelSinCosIntegrals(e);
470        checkHypSinCosIntegrals(e);
471      }
472    }
473
474    private void EvaluateLaggedOperations(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
475      // lag
476      Evaluate(interpreter, ds, "(lagVariable 1.0 a -1) ", 1, ds.GetDoubleValue("A", 0));
477      Evaluate(interpreter, ds, "(lagVariable 1.0 a -1) ", 2, ds.GetDoubleValue("A", 1));
478      Evaluate(interpreter, ds, "(lagVariable 1.0 a 0) ", 2, ds.GetDoubleValue("A", 2));
479      Evaluate(interpreter, ds, "(lagVariable 1.0 a 1) ", 0, ds.GetDoubleValue("A", 1));
480
481      // integral
482      Evaluate(interpreter, ds, "(integral -1.0 (variable 1.0 a)) ", 1, ds.GetDoubleValue("A", 0) + ds.GetDoubleValue("A", 1));
483      Evaluate(interpreter, ds, "(integral -1.0 (lagVariable 1.0 a 1)) ", 1, ds.GetDoubleValue("A", 1) + ds.GetDoubleValue("A", 2));
484      Evaluate(interpreter, ds, "(integral -2.0 (variable 1.0 a)) ", 2, ds.GetDoubleValue("A", 0) + ds.GetDoubleValue("A", 1) + ds.GetDoubleValue("A", 2));
485      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));
486      Evaluate(interpreter, ds, "(integral -2.0 3.0)", 1, 9.0);
487
488      // derivative
489      // (f_0 + 2 * f_1 - 2 * f_3 - f_4) / 8; // h = 1
490      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);
491      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);
492      Evaluate(interpreter, ds, "(diff (* (variable 1.0 a) (variable 1.0 b)))", 5, +
493        (ds.GetDoubleValue("A", 5) * ds.GetDoubleValue("B", 5) +
494        2 * ds.GetDoubleValue("A", 4) * ds.GetDoubleValue("B", 4) -
495        2 * ds.GetDoubleValue("A", 2) * ds.GetDoubleValue("B", 2) -
496        ds.GetDoubleValue("A", 1) * ds.GetDoubleValue("B", 1)) / 8.0);
497      Evaluate(interpreter, ds, "(diff -2.0 3.0)", 5, 0.0);
498
499      // timelag
500      Evaluate(interpreter, ds, "(lag -1.0 (lagVariable 1.0 a 2)) ", 1, ds.GetDoubleValue("A", 2));
501      Evaluate(interpreter, ds, "(lag -2.0 (lagVariable 1.0 a 2)) ", 2, ds.GetDoubleValue("A", 2));
502      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));
503      Evaluate(interpreter, ds, "(lag -2.0 3.0)", 1, 3.0);
504    }
505
506    private void EvaluateOperations(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds) {
507      // addition
508      Evaluate(interpreter, ds, "(+ (variable 2.0 a ))", 1, 4.0);
509      Evaluate(interpreter, ds, "(+ (variable 2.0 a ) (variable 3.0 b ))", 0, 5.0);
510      Evaluate(interpreter, ds, "(+ (variable 2.0 a ) (variable 3.0 b ))", 1, 10.0);
511      Evaluate(interpreter, ds, "(+ (variable 2.0 a) (variable 3.0 b ))", 2, 8.0);
512      Evaluate(interpreter, ds, "(+ 8.0 2.0 2.0)", 0, 12.0);
513
514      // subtraction
515      Evaluate(interpreter, ds, "(- (variable 2.0 a ))", 1, -4.0);
516      Evaluate(interpreter, ds, "(- (variable 2.0 a ) (variable 3.0 b))", 0, -1.0);
517      Evaluate(interpreter, ds, "(- (variable 2.0 a ) (variable 3.0 b ))", 1, -2.0);
518      Evaluate(interpreter, ds, "(- (variable 2.0 a ) (variable 3.0 b ))", 2, -4.0);
519      Evaluate(interpreter, ds, "(- 8.0 2.0 2.0)", 0, 4.0);
520
521      // multiplication
522      Evaluate(interpreter, ds, "(* (variable 2.0 a ))", 0, 2.0);
523      Evaluate(interpreter, ds, "(* (variable 2.0 a ) (variable 3.0 b ))", 0, 6.0);
524      Evaluate(interpreter, ds, "(* (variable 2.0 a ) (variable 3.0 b ))", 1, 24.0);
525      Evaluate(interpreter, ds, "(* (variable 2.0 a ) (variable 3.0 b ))", 2, 12.0);
526      Evaluate(interpreter, ds, "(* 8.0 2.0 2.0)", 0, 32.0);
527
528      // division
529      Evaluate(interpreter, ds, "(/ (variable 2.0 a ))", 1, 1.0 / 4.0);
530      Evaluate(interpreter, ds, "(/ (variable 2.0 a ) 2.0)", 0, 1.0);
531      Evaluate(interpreter, ds, "(/ (variable 2.0 a ) 2.0)", 1, 2.0);
532      Evaluate(interpreter, ds, "(/ (variable 3.0 b ) 2.0)", 2, 3.0);
533      Evaluate(interpreter, ds, "(/ 8.0 2.0 2.0)", 0, 2.0);
534
535      // gt
536      Evaluate(interpreter, ds, "(> (variable 2.0 a) 2.0)", 0, -1.0);
537      Evaluate(interpreter, ds, "(> 2.0 (variable 2.0 a))", 0, -1.0);
538      Evaluate(interpreter, ds, "(> (variable 2.0 a) 1.9)", 0, 1.0);
539      Evaluate(interpreter, ds, "(> 1.9 (variable 2.0 a))", 0, -1.0);
540      Evaluate(interpreter, ds, "(> (log -1.0) (log -1.0))", 0, -1.0); // (> nan nan) should be false
541
542      // lt
543      Evaluate(interpreter, ds, "(< (variable 2.0 a) 2.0)", 0, -1.0);
544      Evaluate(interpreter, ds, "(< 2.0 (variable 2.0 a))", 0, -1.0);
545      Evaluate(interpreter, ds, "(< (variable 2.0 a) 1.9)", 0, -1.0);
546      Evaluate(interpreter, ds, "(< 1.9 (variable 2.0 a))", 0, 1.0);
547      Evaluate(interpreter, ds, "(< (log -1.0) (log -1.0))", 0, -1.0); // (< nan nan) should be false
548
549      // If
550      Evaluate(interpreter, ds, "(if -10.0 2.0 3.0)", 0, 3.0);
551      Evaluate(interpreter, ds, "(if -1.0 2.0 3.0)", 0, 3.0);
552      Evaluate(interpreter, ds, "(if 0.0 2.0 3.0)", 0, 3.0);
553      Evaluate(interpreter, ds, "(if 1.0 2.0 3.0)", 0, 2.0);
554      Evaluate(interpreter, ds, "(if 10.0 2.0 3.0)", 0, 2.0);
555      Evaluate(interpreter, ds, "(if (log -1.0) 2.0 3.0)", 0, 3.0); // if(nan) should return the else branch
556
557      // NOT
558      Evaluate(interpreter, ds, "(not -1.0)", 0, 1.0);
559      Evaluate(interpreter, ds, "(not -2.0)", 0, 1.0);
560      Evaluate(interpreter, ds, "(not 1.0)", 0, -1.0);
561      Evaluate(interpreter, ds, "(not 2.0)", 0, -1.0);
562      Evaluate(interpreter, ds, "(not 0.0)", 0, 1.0);
563      Evaluate(interpreter, ds, "(not (log -1.0))", 0, 1.0);
564
565      // AND
566      Evaluate(interpreter, ds, "(and -1.0 -2.0)", 0, -1.0);
567      Evaluate(interpreter, ds, "(and -1.0 2.0)", 0, -1.0);
568      Evaluate(interpreter, ds, "(and 1.0 -2.0)", 0, -1.0);
569      Evaluate(interpreter, ds, "(and 1.0 0.0)", 0, -1.0);
570      Evaluate(interpreter, ds, "(and 0.0 0.0)", 0, -1.0);
571      Evaluate(interpreter, ds, "(and 1.0 2.0)", 0, 1.0);
572      Evaluate(interpreter, ds, "(and 1.0 2.0 3.0)", 0, 1.0);
573      Evaluate(interpreter, ds, "(and 1.0 -2.0 3.0)", 0, -1.0);
574      Evaluate(interpreter, ds, "(and (log -1.0))", 0, -1.0); // (and NaN)
575      Evaluate(interpreter, ds, "(and (log -1.0)  1.0)", 0, -1.0); // (and NaN 1.0)
576
577      // OR
578      Evaluate(interpreter, ds, "(or -1.0 -2.0)", 0, -1.0);
579      Evaluate(interpreter, ds, "(or -1.0 2.0)", 0, 1.0);
580      Evaluate(interpreter, ds, "(or 1.0 -2.0)", 0, 1.0);
581      Evaluate(interpreter, ds, "(or 1.0 2.0)", 0, 1.0);
582      Evaluate(interpreter, ds, "(or 0.0 0.0)", 0, -1.0);
583      Evaluate(interpreter, ds, "(or -1.0 -2.0 -3.0)", 0, -1.0);
584      Evaluate(interpreter, ds, "(or -1.0 -2.0 3.0)", 0, 1.0);
585      Evaluate(interpreter, ds, "(or (log -1.0))", 0, -1.0); // (or NaN)
586      Evaluate(interpreter, ds, "(or (log -1.0)  1.0)", 0, -1.0); // (or NaN 1.0)
587
588      // XOR
589      Evaluate(interpreter, ds, "(xor -1.0 -2.0)", 0, -1.0);
590      Evaluate(interpreter, ds, "(xor -1.0 2.0)", 0, 1.0);
591      Evaluate(interpreter, ds, "(xor 1.0 -2.0)", 0, 1.0);
592      Evaluate(interpreter, ds, "(xor 1.0 2.0)", 0, -1.0);
593      Evaluate(interpreter, ds, "(xor 0.0 0.0)", 0, -1.0);
594      Evaluate(interpreter, ds, "(xor -1.0 -2.0 -3.0)", 0, -1.0);
595      Evaluate(interpreter, ds, "(xor -1.0 -2.0 3.0)", 0, 1.0);
596      Evaluate(interpreter, ds, "(xor -1.0 2.0 3.0)", 0, -1.0);
597      Evaluate(interpreter, ds, "(xor 1.0 2.0 3.0)", 0, 1.0);
598      Evaluate(interpreter, ds, "(xor (log -1.0))", 0, -1.0);
599      Evaluate(interpreter, ds, "(xor (log -1.0)  1.0)", 0, 1.0);
600
601      // sin, cos, tan
602      Evaluate(interpreter, ds, "(sin " + Math.PI.ToString(NumberFormatInfo.InvariantInfo) + ")", 0, 0.0);
603      Evaluate(interpreter, ds, "(sin 0.0)", 0, 0.0);
604      Evaluate(interpreter, ds, "(cos " + Math.PI.ToString(NumberFormatInfo.InvariantInfo) + ")", 0, -1.0);
605      Evaluate(interpreter, ds, "(cos 0.0)", 0, 1.0);
606      Evaluate(interpreter, ds, "(tan " + Math.PI.ToString(NumberFormatInfo.InvariantInfo) + ")", 0, Math.Tan(Math.PI));
607      Evaluate(interpreter, ds, "(tan 0.0)", 0, Math.Tan(Math.PI));
608
609      // exp, log
610      Evaluate(interpreter, ds, "(log (exp 7.0))", 0, Math.Log(Math.Exp(7)));
611      Evaluate(interpreter, ds, "(exp (log 7.0))", 0, Math.Exp(Math.Log(7)));
612      Evaluate(interpreter, ds, "(log -3.0)", 0, Math.Log(-3));
613
614      // power
615      Evaluate(interpreter, ds, "(pow 2.0 3.0)", 0, 8.0);
616      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)
617      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)
618      Evaluate(interpreter, ds, "(pow -2.0 3.0)", 0, -8.0);
619      Evaluate(interpreter, ds, "(pow 2.0 -3.0)", 0, 1.0 / 8.0);
620      Evaluate(interpreter, ds, "(pow -2.0 -3.0)", 0, -1.0 / 8.0);
621
622      // root
623      Evaluate(interpreter, ds, "(root 9.0 2.0)", 0, 3.0);
624      Evaluate(interpreter, ds, "(root 27.0 3.0)", 0, 3.0);
625      Evaluate(interpreter, ds, "(root 2.0 -3.0)", 0, Math.Pow(2.0, -1.0 / 3.0));
626
627      // mean
628      Evaluate(interpreter, ds, "(mean -1.0 1.0 -1.0)", 0, -1.0 / 3.0);
629    }
630
631    private void Evaluate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, IDataset ds, string expr, int index, double expected) {
632      var importer = new SymbolicExpressionImporter();
633      ISymbolicExpressionTree tree = importer.Import(expr);
634
635      double actual = interpreter.GetSymbolicExpressionTreeValues(tree, ds, Enumerable.Range(index, 1)).First();
636
637      Assert.IsFalse(double.IsNaN(actual) && !double.IsNaN(expected));
638      Assert.IsFalse(!double.IsNaN(actual) && double.IsNaN(expected));
639      if (!double.IsNaN(actual) && !double.IsNaN(expected))
640        Assert.AreEqual(expected, actual, 1.0E-12, expr);
641    }
642  }
643}
Note: See TracBrowser for help on using the repository browser.