Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeILEmittingInterpreter.cs @ 10037

Last change on this file since 10037 was 9828, checked in by mkommend, 11 years ago

#2021: Integrated the linear interpreter in the trunk and restructed interpreter unit tests.

File size: 33.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Linq;
25using System.Reflection;
26using System.Reflection.Emit;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
35  [StorableClass]
36  [Item("SymbolicDataAnalysisExpressionTreeILEmittingInterpreter", "Interpreter for symbolic expression trees.")]
37  public sealed class SymbolicDataAnalysisExpressionTreeILEmittingInterpreter : ParameterizedNamedItem, ISymbolicDataAnalysisExpressionTreeInterpreter {
38    private static readonly Type thisType = typeof(SymbolicDataAnalysisExpressionTreeILEmittingInterpreter);
39    internal delegate double CompiledFunction(int sampleIndex, IList<double>[] columns);
40
41    #region method infos
42    private static MethodInfo listGetValue = typeof(IList<double>).GetProperty("Item", new Type[] { typeof(int) }).GetGetMethod();
43
44    private static MethodInfo cos = typeof(Math).GetMethod("Cos", new Type[] { typeof(double) });
45    private static MethodInfo sin = typeof(Math).GetMethod("Sin", new Type[] { typeof(double) });
46    private static MethodInfo tan = typeof(Math).GetMethod("Tan", new Type[] { typeof(double) });
47    private static MethodInfo exp = typeof(Math).GetMethod("Exp", new Type[] { typeof(double) });
48    private static MethodInfo log = typeof(Math).GetMethod("Log", new Type[] { typeof(double) });
49    private static MethodInfo power = typeof(Math).GetMethod("Pow", new Type[] { typeof(double), typeof(double) });
50    private static MethodInfo round = typeof(Math).GetMethod("Round", new Type[] { typeof(double) });
51    private static MethodInfo sqrt = typeof(Math).GetMethod("Sqrt", new Type[] { typeof(double) });
52
53    private static MethodInfo airyA = thisType.GetMethod("AiryA", new Type[] { typeof(double) });
54    private static MethodInfo airyB = thisType.GetMethod("AiryB", new Type[] { typeof(double) });
55    private static MethodInfo gamma = thisType.GetMethod("Gamma", new Type[] { typeof(double) });
56    private static MethodInfo psi = thisType.GetMethod("Psi", new Type[] { typeof(double) });
57    private static MethodInfo dawson = thisType.GetMethod("Dawson", new Type[] { typeof(double) });
58    private static MethodInfo expIntegralEi = thisType.GetMethod("ExpIntegralEi", new Type[] { typeof(double) });
59    private static MethodInfo sinIntegral = thisType.GetMethod("SinIntegral", new Type[] { typeof(double) });
60    private static MethodInfo cosIntegral = thisType.GetMethod("CosIntegral", new Type[] { typeof(double) });
61    private static MethodInfo hypSinIntegral = thisType.GetMethod("HypSinIntegral", new Type[] { typeof(double) });
62    private static MethodInfo hypCosIntegral = thisType.GetMethod("HypCosIntegral", new Type[] { typeof(double) });
63    private static MethodInfo fresnelCosIntegral = thisType.GetMethod("FresnelCosIntegral", new Type[] { typeof(double) });
64    private static MethodInfo fresnelSinIntegral = thisType.GetMethod("FresnelSinIntegral", new Type[] { typeof(double) });
65    private static MethodInfo norm = thisType.GetMethod("Norm", new Type[] { typeof(double) });
66    private static MethodInfo erf = thisType.GetMethod("Erf", new Type[] { typeof(double) });
67    private static MethodInfo bessel = thisType.GetMethod("Bessel", new Type[] { typeof(double) });
68    #endregion
69
70    private const string CheckExpressionsWithIntervalArithmeticParameterName = "CheckExpressionsWithIntervalArithmetic";
71    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
72
73    public override bool CanChangeName {
74      get { return false; }
75    }
76
77    public override bool CanChangeDescription {
78      get { return false; }
79    }
80
81    #region parameter properties
82
83    public IValueParameter<BoolValue> CheckExpressionsWithIntervalArithmeticParameter {
84      get { return (IValueParameter<BoolValue>)Parameters[CheckExpressionsWithIntervalArithmeticParameterName]; }
85    }
86
87    public IValueParameter<IntValue> EvaluatedSolutionsParameter {
88      get { return (IValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
89    }
90
91    #endregion
92
93    #region properties
94
95    public BoolValue CheckExpressionsWithIntervalArithmetic {
96      get { return CheckExpressionsWithIntervalArithmeticParameter.Value; }
97      set { CheckExpressionsWithIntervalArithmeticParameter.Value = value; }
98    }
99
100    public IntValue EvaluatedSolutions {
101      get { return EvaluatedSolutionsParameter.Value; }
102      set { EvaluatedSolutionsParameter.Value = value; }
103    }
104
105    #endregion
106
107
108    [StorableConstructor]
109    private SymbolicDataAnalysisExpressionTreeILEmittingInterpreter(bool deserializing) : base(deserializing) { }
110
111    private SymbolicDataAnalysisExpressionTreeILEmittingInterpreter(SymbolicDataAnalysisExpressionTreeILEmittingInterpreter original, Cloner cloner) : base(original, cloner) { }
112    public override IDeepCloneable Clone(Cloner cloner) {
113      return new SymbolicDataAnalysisExpressionTreeILEmittingInterpreter(this, cloner);
114    }
115
116    public SymbolicDataAnalysisExpressionTreeILEmittingInterpreter()
117      : base("SymbolicDataAnalysisExpressionTreeILEmittingInterpreter", "Interpreter for symbolic expression trees.") {
118      Parameters.Add(new ValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, "Switch that determines if the interpreter checks the validity of expressions with interval arithmetic before evaluating the expression.", new BoolValue(false)));
119      Parameters.Add(new ValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
120    }
121
122    [StorableHook(HookType.AfterDeserialization)]
123    private void AfterDeserialization() {
124      if (!Parameters.ContainsKey(EvaluatedSolutionsParameterName))
125        Parameters.Add(new ValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
126    }
127
128    #region IStatefulItem
129
130    public void InitializeState() {
131      EvaluatedSolutions.Value = 0;
132    }
133
134    public void ClearState() {
135      EvaluatedSolutions.Value = 0;
136    }
137
138    #endregion
139
140    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
141      if (CheckExpressionsWithIntervalArithmetic.Value)
142        throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter.");
143
144      EvaluatedSolutions.Value++; // increment the evaluated solutions counter
145      var state = PrepareInterpreterState(tree, dataset);
146
147      Type[] methodArgs = { typeof(int), typeof(IList<double>[]) };
148      DynamicMethod testFun = new DynamicMethod("TestFun", typeof(double), methodArgs, typeof(SymbolicDataAnalysisExpressionTreeILEmittingInterpreter).Module);
149
150      ILGenerator il = testFun.GetILGenerator();
151      CompileInstructions(il, state, dataset);
152      il.Emit(System.Reflection.Emit.OpCodes.Conv_R8);
153      il.Emit(System.Reflection.Emit.OpCodes.Ret);
154      var function = (CompiledFunction)testFun.CreateDelegate(typeof(CompiledFunction));
155
156      IList<double>[] columns = dataset.DoubleVariables.Select(v => dataset.GetReadOnlyDoubleValues(v)).ToArray();
157
158      foreach (var row in rows) {
159        yield return function(row, columns);
160      }
161    }
162
163    private InterpreterState PrepareInterpreterState(ISymbolicExpressionTree tree, Dataset dataset) {
164      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
165      Dictionary<string, int> doubleVariableNames = dataset.DoubleVariables.Select((x, i) => new { x, i }).ToDictionary(e => e.x, e => e.i);
166      int necessaryArgStackSize = 0;
167      foreach (Instruction instr in code) {
168        if (instr.opCode == OpCodes.Variable) {
169          var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
170          instr.data = doubleVariableNames[variableTreeNode.VariableName];
171        } else if (instr.opCode == OpCodes.LagVariable) {
172          var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
173          instr.data = doubleVariableNames[laggedVariableTreeNode.VariableName];
174        } else if (instr.opCode == OpCodes.VariableCondition) {
175          var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
176          instr.data = doubleVariableNames[variableConditionTreeNode.VariableName];
177        } else if (instr.opCode == OpCodes.Call) {
178          necessaryArgStackSize += instr.nArguments + 1;
179        }
180      }
181      return new InterpreterState(code, necessaryArgStackSize);
182    }
183
184    private void CompileInstructions(ILGenerator il, InterpreterState state, Dataset ds) {
185      Instruction currentInstr = state.NextInstruction();
186      int nArgs = currentInstr.nArguments;
187
188      switch (currentInstr.opCode) {
189        case OpCodes.Add: {
190            if (nArgs > 0) {
191              CompileInstructions(il, state, ds);
192            }
193            for (int i = 1; i < nArgs; i++) {
194              CompileInstructions(il, state, ds);
195              il.Emit(System.Reflection.Emit.OpCodes.Add);
196            }
197            return;
198          }
199        case OpCodes.Sub: {
200            if (nArgs == 1) {
201              CompileInstructions(il, state, ds);
202              il.Emit(System.Reflection.Emit.OpCodes.Neg);
203              return;
204            }
205            if (nArgs > 0) {
206              CompileInstructions(il, state, ds);
207            }
208            for (int i = 1; i < nArgs; i++) {
209              CompileInstructions(il, state, ds);
210              il.Emit(System.Reflection.Emit.OpCodes.Sub);
211            }
212            return;
213          }
214        case OpCodes.Mul: {
215            if (nArgs > 0) {
216              CompileInstructions(il, state, ds);
217            }
218            for (int i = 1; i < nArgs; i++) {
219              CompileInstructions(il, state, ds);
220              il.Emit(System.Reflection.Emit.OpCodes.Mul);
221            }
222            return;
223          }
224        case OpCodes.Div: {
225            if (nArgs == 1) {
226              il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0);
227              CompileInstructions(il, state, ds);
228              il.Emit(System.Reflection.Emit.OpCodes.Div);
229              return;
230            }
231            if (nArgs > 0) {
232              CompileInstructions(il, state, ds);
233            }
234            for (int i = 1; i < nArgs; i++) {
235              CompileInstructions(il, state, ds);
236              il.Emit(System.Reflection.Emit.OpCodes.Div);
237            }
238            return;
239          }
240        case OpCodes.Average: {
241            CompileInstructions(il, state, ds);
242            for (int i = 1; i < nArgs; i++) {
243              CompileInstructions(il, state, ds);
244              il.Emit(System.Reflection.Emit.OpCodes.Add);
245            }
246            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, nArgs);
247            il.Emit(System.Reflection.Emit.OpCodes.Div);
248            return;
249          }
250        case OpCodes.Cos: {
251            CompileInstructions(il, state, ds);
252            il.Emit(System.Reflection.Emit.OpCodes.Call, cos);
253            return;
254          }
255        case OpCodes.Sin: {
256            CompileInstructions(il, state, ds);
257            il.Emit(System.Reflection.Emit.OpCodes.Call, sin);
258            return;
259          }
260        case OpCodes.Tan: {
261            CompileInstructions(il, state, ds);
262            il.Emit(System.Reflection.Emit.OpCodes.Call, tan);
263            return;
264          }
265        case OpCodes.Power: {
266            CompileInstructions(il, state, ds);
267            CompileInstructions(il, state, ds);
268            il.Emit(System.Reflection.Emit.OpCodes.Call, round);
269            il.Emit(System.Reflection.Emit.OpCodes.Call, power);
270            return;
271          }
272        case OpCodes.Root: {
273            CompileInstructions(il, state, ds);
274            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // 1 / round(...)
275            CompileInstructions(il, state, ds);
276            il.Emit(System.Reflection.Emit.OpCodes.Call, round);
277            il.Emit(System.Reflection.Emit.OpCodes.Div);
278            il.Emit(System.Reflection.Emit.OpCodes.Call, power);
279            return;
280          }
281        case OpCodes.Exp: {
282            CompileInstructions(il, state, ds);
283            il.Emit(System.Reflection.Emit.OpCodes.Call, exp);
284            return;
285          }
286        case OpCodes.Log: {
287            CompileInstructions(il, state, ds);
288            il.Emit(System.Reflection.Emit.OpCodes.Call, log);
289            return;
290          }
291        case OpCodes.Square: {
292            CompileInstructions(il, state, ds);
293            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0);
294            il.Emit(System.Reflection.Emit.OpCodes.Call, power);
295            return;
296          }
297        case OpCodes.SquareRoot: {
298            CompileInstructions(il, state, ds);
299            il.Emit(System.Reflection.Emit.OpCodes.Call, sqrt);
300            return;
301          }
302        case OpCodes.AiryA: {
303            CompileInstructions(il, state, ds);
304            il.Emit(System.Reflection.Emit.OpCodes.Call, airyA);
305            return;
306          }
307        case OpCodes.AiryB: {
308            CompileInstructions(il, state, ds);
309            il.Emit(System.Reflection.Emit.OpCodes.Call, airyB);
310            return;
311          }
312        case OpCodes.Bessel: {
313            CompileInstructions(il, state, ds);
314            il.Emit(System.Reflection.Emit.OpCodes.Call, bessel);
315            return;
316          }
317        case OpCodes.CosineIntegral: {
318            CompileInstructions(il, state, ds);
319            il.Emit(System.Reflection.Emit.OpCodes.Call, cosIntegral);
320            return;
321          }
322        case OpCodes.Dawson: {
323            CompileInstructions(il, state, ds);
324            il.Emit(System.Reflection.Emit.OpCodes.Call, dawson);
325            return;
326          }
327        case OpCodes.Erf: {
328            CompileInstructions(il, state, ds);
329            il.Emit(System.Reflection.Emit.OpCodes.Call, erf);
330            return;
331          }
332        case OpCodes.ExponentialIntegralEi: {
333            CompileInstructions(il, state, ds);
334            il.Emit(System.Reflection.Emit.OpCodes.Call, expIntegralEi);
335            return;
336          }
337        case OpCodes.FresnelCosineIntegral: {
338            CompileInstructions(il, state, ds);
339            il.Emit(System.Reflection.Emit.OpCodes.Call, fresnelCosIntegral);
340            return;
341          }
342        case OpCodes.FresnelSineIntegral: {
343            CompileInstructions(il, state, ds);
344            il.Emit(System.Reflection.Emit.OpCodes.Call, fresnelSinIntegral);
345            return;
346          }
347        case OpCodes.Gamma: {
348            CompileInstructions(il, state, ds);
349            il.Emit(System.Reflection.Emit.OpCodes.Call, gamma);
350            return;
351          }
352        case OpCodes.HyperbolicCosineIntegral: {
353            CompileInstructions(il, state, ds);
354            il.Emit(System.Reflection.Emit.OpCodes.Call, hypCosIntegral);
355            return;
356          }
357        case OpCodes.HyperbolicSineIntegral: {
358            CompileInstructions(il, state, ds);
359            il.Emit(System.Reflection.Emit.OpCodes.Call, hypSinIntegral);
360            return;
361          }
362        case OpCodes.Norm: {
363            CompileInstructions(il, state, ds);
364            il.Emit(System.Reflection.Emit.OpCodes.Call, norm);
365            return;
366          }
367        case OpCodes.Psi: {
368            CompileInstructions(il, state, ds);
369            il.Emit(System.Reflection.Emit.OpCodes.Call, psi);
370            return;
371          }
372        case OpCodes.SineIntegral: {
373            CompileInstructions(il, state, ds);
374            il.Emit(System.Reflection.Emit.OpCodes.Call, sinIntegral);
375            return;
376          }
377        case OpCodes.IfThenElse: {
378            Label end = il.DefineLabel();
379            Label c1 = il.DefineLabel();
380            CompileInstructions(il, state, ds);
381            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0); // > 0
382            il.Emit(System.Reflection.Emit.OpCodes.Cgt);
383            il.Emit(System.Reflection.Emit.OpCodes.Brfalse, c1);
384            CompileInstructions(il, state, ds);
385            il.Emit(System.Reflection.Emit.OpCodes.Br, end);
386            il.MarkLabel(c1);
387            CompileInstructions(il, state, ds);
388            il.MarkLabel(end);
389            return;
390          }
391        case OpCodes.AND: {
392            Label falseBranch = il.DefineLabel();
393            Label end = il.DefineLabel();
394            CompileInstructions(il, state, ds);
395            for (int i = 1; i < nArgs; i++) {
396              il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0); // > 0
397              il.Emit(System.Reflection.Emit.OpCodes.Cgt);
398              il.Emit(System.Reflection.Emit.OpCodes.Brfalse, falseBranch);
399              CompileInstructions(il, state, ds);
400            }
401            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0); // > 0
402            il.Emit(System.Reflection.Emit.OpCodes.Cgt);
403            il.Emit(System.Reflection.Emit.OpCodes.Brfalse, falseBranch);
404            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // 1
405            il.Emit(System.Reflection.Emit.OpCodes.Br, end);
406            il.MarkLabel(falseBranch);
407            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // -1
408            il.Emit(System.Reflection.Emit.OpCodes.Neg);
409            il.MarkLabel(end);
410            return;
411          }
412        case OpCodes.OR: {
413            Label trueBranch = il.DefineLabel();
414            Label end = il.DefineLabel();
415            Label resultBranch = il.DefineLabel();
416            CompileInstructions(il, state, ds);
417            for (int i = 1; i < nArgs; i++) {
418              Label nextArgBranch = il.DefineLabel();
419              // complex definition because of special properties of NaN 
420              il.Emit(System.Reflection.Emit.OpCodes.Dup);
421              il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0); // <= 0       
422              il.Emit(System.Reflection.Emit.OpCodes.Ble, nextArgBranch);
423              il.Emit(System.Reflection.Emit.OpCodes.Br, resultBranch);
424              il.MarkLabel(nextArgBranch);
425              il.Emit(System.Reflection.Emit.OpCodes.Pop);
426              CompileInstructions(il, state, ds);
427            }
428            il.MarkLabel(resultBranch);
429            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0); // > 0
430            il.Emit(System.Reflection.Emit.OpCodes.Cgt);
431            il.Emit(System.Reflection.Emit.OpCodes.Brtrue, trueBranch);
432            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // -1
433            il.Emit(System.Reflection.Emit.OpCodes.Neg);
434            il.Emit(System.Reflection.Emit.OpCodes.Br, end);
435            il.MarkLabel(trueBranch);
436            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // 1
437            il.MarkLabel(end);
438            return;
439          }
440        case OpCodes.NOT: {
441            CompileInstructions(il, state, ds);
442            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0); // > 0
443            il.Emit(System.Reflection.Emit.OpCodes.Cgt);
444            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // * 2
445            il.Emit(System.Reflection.Emit.OpCodes.Mul);
446            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // - 1
447            il.Emit(System.Reflection.Emit.OpCodes.Sub);
448            il.Emit(System.Reflection.Emit.OpCodes.Neg); // * -1
449            return;
450          }
451        case OpCodes.GT: {
452            CompileInstructions(il, state, ds);
453            CompileInstructions(il, state, ds);
454
455            il.Emit(System.Reflection.Emit.OpCodes.Cgt); // 1 (>) / 0 (otherwise)
456            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // * 2
457            il.Emit(System.Reflection.Emit.OpCodes.Mul);
458            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // - 1
459            il.Emit(System.Reflection.Emit.OpCodes.Sub);
460            return;
461          }
462        case OpCodes.LT: {
463            CompileInstructions(il, state, ds);
464            CompileInstructions(il, state, ds);
465            il.Emit(System.Reflection.Emit.OpCodes.Clt);
466            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // * 2
467            il.Emit(System.Reflection.Emit.OpCodes.Mul);
468            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 1.0); // - 1
469            il.Emit(System.Reflection.Emit.OpCodes.Sub);
470            return;
471          }
472        case OpCodes.TimeLag: {
473            LaggedTreeNode laggedTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
474            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row -= lag
475            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, laggedTreeNode.Lag);
476            il.Emit(System.Reflection.Emit.OpCodes.Add);
477            il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
478            var prevLaggedContext = state.InLaggedContext;
479            state.InLaggedContext = true;
480            CompileInstructions(il, state, ds);
481            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row += lag
482            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, laggedTreeNode.Lag);
483            il.Emit(System.Reflection.Emit.OpCodes.Sub);
484            il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
485            state.InLaggedContext = prevLaggedContext;
486            return;
487          }
488        case OpCodes.Integral: {
489            int savedPc = state.ProgramCounter;
490            LaggedTreeNode laggedTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
491            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row -= lag
492            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, laggedTreeNode.Lag);
493            il.Emit(System.Reflection.Emit.OpCodes.Add);
494            il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
495            var prevLaggedContext = state.InLaggedContext;
496            state.InLaggedContext = true;
497            CompileInstructions(il, state, ds);
498            for (int l = laggedTreeNode.Lag; l < 0; l++) {
499              il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row += lag
500              il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_1);
501              il.Emit(System.Reflection.Emit.OpCodes.Add);
502              il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
503              state.ProgramCounter = savedPc;
504              CompileInstructions(il, state, ds);
505              il.Emit(System.Reflection.Emit.OpCodes.Add);
506            }
507            state.InLaggedContext = prevLaggedContext;
508            return;
509          }
510
511        //mkommend: derivate calculation taken from:
512        //http://www.holoborodko.com/pavel/numerical-methods/numerical-derivative/smooth-low-noise-differentiators/
513        //one sided smooth differentiatior, N = 4
514        // y' = 1/8h (f_i + 2f_i-1, -2 f_i-3 - f_i-4)
515        case OpCodes.Derivative: {
516            int savedPc = state.ProgramCounter;
517            CompileInstructions(il, state, ds);
518            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row --
519            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_M1);
520            il.Emit(System.Reflection.Emit.OpCodes.Add);
521            il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
522            state.ProgramCounter = savedPc;
523            var prevLaggedContext = state.InLaggedContext;
524            state.InLaggedContext = true;
525            CompileInstructions(il, state, ds);
526            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // f_0 + 2 * f_1
527            il.Emit(System.Reflection.Emit.OpCodes.Mul);
528            il.Emit(System.Reflection.Emit.OpCodes.Add);
529
530            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row -=2
531            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_2);
532            il.Emit(System.Reflection.Emit.OpCodes.Sub);
533            il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
534            state.ProgramCounter = savedPc;
535            CompileInstructions(il, state, ds);
536            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 2.0); // f_0 + 2 * f_1 - 2 * f_3
537            il.Emit(System.Reflection.Emit.OpCodes.Mul);
538            il.Emit(System.Reflection.Emit.OpCodes.Sub);
539
540            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row --
541            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_M1);
542            il.Emit(System.Reflection.Emit.OpCodes.Add);
543            il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
544            state.ProgramCounter = savedPc;
545            CompileInstructions(il, state, ds);
546            il.Emit(System.Reflection.Emit.OpCodes.Sub); // f_0 + 2 * f_1 - 2 * f_3 - f_4
547            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, 8.0); // / 8
548            il.Emit(System.Reflection.Emit.OpCodes.Div);
549
550            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // row +=4
551            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_4);
552            il.Emit(System.Reflection.Emit.OpCodes.Add);
553            il.Emit(System.Reflection.Emit.OpCodes.Starg, 0);
554            state.InLaggedContext = prevLaggedContext;
555            return;
556          }
557        case OpCodes.Call: {
558            throw new NotSupportedException(
559              "Automatically defined functions are not supported by the SymbolicDataAnalysisTreeILEmittingInterpreter. Either turn of ADFs or change the interpeter.");
560          }
561        case OpCodes.Arg: {
562            throw new NotSupportedException(
563              "Automatically defined functions are not supported by the SymbolicDataAnalysisTreeILEmittingInterpreter. Either turn of ADFs or change the interpeter.");
564          }
565        case OpCodes.Variable: {
566            VariableTreeNode varNode = (VariableTreeNode)currentInstr.dynamicNode;
567            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1); // load columns array
568            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int)currentInstr.data);
569            // load correct column of the current variable
570            il.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);
571            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // rowIndex
572            if (!state.InLaggedContext) {
573              il.Emit(System.Reflection.Emit.OpCodes.Call, listGetValue);
574              il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, varNode.Weight); // load weight
575              il.Emit(System.Reflection.Emit.OpCodes.Mul);
576            } else {
577              var nanResult = il.DefineLabel();
578              var normalResult = il.DefineLabel();
579              il.Emit(System.Reflection.Emit.OpCodes.Dup);
580              il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0);
581              il.Emit(System.Reflection.Emit.OpCodes.Blt, nanResult);
582              il.Emit(System.Reflection.Emit.OpCodes.Dup);
583              il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, ds.Rows);
584              il.Emit(System.Reflection.Emit.OpCodes.Bge, nanResult);
585              il.Emit(System.Reflection.Emit.OpCodes.Call, listGetValue);
586              il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, varNode.Weight); // load weight
587              il.Emit(System.Reflection.Emit.OpCodes.Mul);
588              il.Emit(System.Reflection.Emit.OpCodes.Br, normalResult);
589              il.MarkLabel(nanResult);
590              il.Emit(System.Reflection.Emit.OpCodes.Pop); // rowIndex
591              il.Emit(System.Reflection.Emit.OpCodes.Pop); // column reference
592              il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, double.NaN);
593              il.MarkLabel(normalResult);
594            }
595            return;
596          }
597        case OpCodes.LagVariable: {
598            var nanResult = il.DefineLabel();
599            var normalResult = il.DefineLabel();
600            LaggedVariableTreeNode varNode = (LaggedVariableTreeNode)currentInstr.dynamicNode;
601            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_1); // load columns array
602            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int)currentInstr.data);
603            // load correct column of the current variable
604            il.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);
605            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, varNode.Lag); // lag
606            il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); // rowIndex
607            il.Emit(System.Reflection.Emit.OpCodes.Add); // actualRowIndex = rowIndex + sampleOffset
608            il.Emit(System.Reflection.Emit.OpCodes.Dup);
609            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0);
610            il.Emit(System.Reflection.Emit.OpCodes.Blt, nanResult);
611            il.Emit(System.Reflection.Emit.OpCodes.Dup);
612            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, ds.Rows);
613            il.Emit(System.Reflection.Emit.OpCodes.Bge, nanResult);
614            il.Emit(System.Reflection.Emit.OpCodes.Call, listGetValue);
615            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, varNode.Weight); // load weight
616            il.Emit(System.Reflection.Emit.OpCodes.Mul);
617            il.Emit(System.Reflection.Emit.OpCodes.Br, normalResult);
618            il.MarkLabel(nanResult);
619            il.Emit(System.Reflection.Emit.OpCodes.Pop); // sample index
620            il.Emit(System.Reflection.Emit.OpCodes.Pop); // column reference
621            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, double.NaN);
622            il.MarkLabel(normalResult);
623            return;
624          }
625        case OpCodes.Constant: {
626            ConstantTreeNode constNode = (ConstantTreeNode)currentInstr.dynamicNode;
627            il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, constNode.Value);
628            return;
629          }
630
631        //mkommend: this symbol uses the logistic function f(x) = 1 / (1 + e^(-alpha * x) )
632        //to determine the relative amounts of the true and false branch see http://en.wikipedia.org/wiki/Logistic_function
633        case OpCodes.VariableCondition: {
634            throw new NotSupportedException("Interpretation of symbol " + currentInstr.dynamicNode.Symbol.Name +
635                                            " is not supported by the SymbolicDataAnalysisTreeILEmittingInterpreter");
636          }
637        default:
638          throw new NotSupportedException("Interpretation of symbol " + currentInstr.dynamicNode.Symbol.Name +
639                                          " is not supported by the SymbolicDataAnalysisTreeILEmittingInterpreter");
640      }
641    }
642
643    public static double AiryA(double x) {
644      if (double.IsNaN(x)) return double.NaN;
645      double ai, aip, bi, bip;
646      alglib.airy(x, out ai, out aip, out bi, out bip);
647      return ai;
648    }
649
650    public static double AiryB(double x) {
651      if (double.IsNaN(x)) return double.NaN;
652      double ai, aip, bi, bip;
653      alglib.airy(x, out ai, out aip, out bi, out bip);
654      return bi;
655    }
656    public static double Dawson(double x) {
657      if (double.IsNaN(x)) return double.NaN;
658      return alglib.dawsonintegral(x);
659    }
660
661    public static double Gamma(double x) {
662      if (double.IsNaN(x)) return double.NaN;
663      return alglib.gammafunction(x);
664    }
665
666    public static double Psi(double x) {
667      if (double.IsNaN(x)) return double.NaN;
668      else if (x <= 0 && (Math.Floor(x) - x).IsAlmost(0)) return double.NaN;
669      return alglib.psi(x);
670    }
671
672    public static double ExpIntegralEi(double x) {
673      if (double.IsNaN(x)) return double.NaN;
674      return alglib.exponentialintegralei(x);
675    }
676
677    public static double SinIntegral(double x) {
678      if (double.IsNaN(x)) return double.NaN;
679      double si, ci;
680      alglib.sinecosineintegrals(x, out si, out ci);
681      return si;
682    }
683
684    public static double CosIntegral(double x) {
685      if (double.IsNaN(x)) return double.NaN;
686      double si, ci;
687      alglib.sinecosineintegrals(x, out si, out ci);
688      return ci;
689    }
690
691    public static double HypSinIntegral(double x) {
692      if (double.IsNaN(x)) return double.NaN;
693      double shi, chi;
694      alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
695      return shi;
696    }
697
698    public static double HypCosIntegral(double x) {
699      if (double.IsNaN(x)) return double.NaN;
700      double shi, chi;
701      alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
702      return chi;
703    }
704
705    public static double FresnelCosIntegral(double x) {
706      if (double.IsNaN(x)) return double.NaN;
707      double c = 0, s = 0;
708      alglib.fresnelintegral(x, ref c, ref s);
709      return c;
710    }
711
712    public static double FresnelSinIntegral(double x) {
713      if (double.IsNaN(x)) return double.NaN;
714      double c = 0, s = 0;
715      alglib.fresnelintegral(x, ref c, ref s);
716      return s;
717    }
718
719    public static double Norm(double x) {
720      if (double.IsNaN(x)) return double.NaN;
721      return alglib.normaldistribution(x);
722    }
723
724    public static double Erf(double x) {
725      if (double.IsNaN(x)) return double.NaN;
726      return alglib.errorfunction(x);
727    }
728
729    public static double Bessel(double x) {
730      if (double.IsNaN(x)) return double.NaN;
731      return alglib.besseli0(x);
732    }
733  }
734}
Note: See TracBrowser for help on using the repository browser.