Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2929_PrioritizedGrammarEnumeration/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4/SymbolicDataAnalysisExpressionTreeInterpreterTest.cs @ 16371

Last change on this file since 16371 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

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