Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionCompiledTreeInterpreter.cs @ 18160

Last change on this file since 18160 was 18132, checked in by gkronber, 3 years ago

#3140: merged r18091:18131 from branch to trunk

File size: 33.7 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.Linq;
25using System.Linq.Expressions;
26using System.Reflection;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
31using HeuristicLab.Parameters;
32using HEAL.Attic;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
35  [StorableType("DFA06F28-E224-4D93-9907-69792D24D1F9")]
36  [Item("SymbolicDataAnalysisExpressionCompiledTreeInterpreter", "Interpreter that converts the tree into a Linq.Expression then compiles it.")]
37  public sealed class SymbolicDataAnalysisExpressionCompiledTreeInterpreter : ParameterizedNamedItem, ISymbolicDataAnalysisExpressionTreeInterpreter {
38    private const string CheckExpressionsWithIntervalArithmeticParameterName = "CheckExpressionsWithIntervalArithmetic";
39    private const string CheckExpressionsWithIntervalArithmeticParameterDescription = "Switch that determines if the interpreter checks the validity of expressions with interval arithmetic before evaluating the expression.";
40    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
41
42    #region method info for the commonly called functions
43    private static readonly MethodInfo Abs = typeof(Math).GetMethod("Abs", new[] { typeof(double) });
44    private static readonly MethodInfo Sin = typeof(Math).GetMethod("Sin", new[] { typeof(double) });
45    private static readonly MethodInfo Cos = typeof(Math).GetMethod("Cos", new[] { typeof(double) });
46    private static readonly MethodInfo Tan = typeof(Math).GetMethod("Tan", new[] { typeof(double) });
47    private static readonly MethodInfo Tanh = typeof(Math).GetMethod("Tanh", new[] { typeof(double) });
48    private static readonly MethodInfo Sqrt = typeof(Math).GetMethod("Sqrt", new[] { typeof(double) });
49    private static readonly MethodInfo Floor = typeof(Math).GetMethod("Floor", new[] { typeof(double) });
50    private static readonly MethodInfo Round = typeof(Math).GetMethod("Round", new[] { typeof(double) });
51    private static readonly MethodInfo Exp = typeof(Math).GetMethod("Exp", new[] { typeof(double) });
52    private static readonly MethodInfo Log = typeof(Math).GetMethod("Log", new[] { typeof(double) });
53    private static readonly MethodInfo IsNaN = typeof(double).GetMethod("IsNaN");
54    private static readonly MethodInfo IsAlmost = typeof(DoubleExtensions).GetMethod("IsAlmost", new Type[] { typeof(double), typeof(double)});
55    private static readonly MethodInfo Gamma = typeof(alglib).GetMethod("gammafunction", new[] { typeof(double) });
56    private static readonly MethodInfo Psi = typeof(alglib).GetMethod("psi", new[] { typeof(double) });
57    private static readonly MethodInfo DawsonIntegral = typeof(alglib).GetMethod("dawsonintegral", new[] { typeof(double) });
58    private static readonly MethodInfo ExponentialIntegralEi = typeof(alglib).GetMethod("exponentialintegralei", new[] { typeof(double) });
59    private static readonly MethodInfo SineCosineIntegrals = typeof(alglib).GetMethod("sinecosineintegrals", new[] { typeof(double), typeof(double).MakeByRefType(), typeof(double).MakeByRefType() });
60    private static readonly MethodInfo HyperbolicSineCosineIntegrals = typeof(alglib).GetMethod("hyperbolicsinecosineintegrals", new[] { typeof(double), typeof(double).MakeByRefType(), typeof(double).MakeByRefType() });
61    private static readonly MethodInfo FresnelIntegral = typeof(alglib).GetMethod("fresnelintegral", new[] { typeof(double), typeof(double).MakeByRefType(), typeof(double).MakeByRefType() });
62    private static readonly MethodInfo Airy = typeof(alglib).GetMethod("airy", new[] { typeof(double), typeof(double).MakeByRefType(), typeof(double).MakeByRefType(), typeof(double).MakeByRefType(), typeof(double).MakeByRefType() });
63    private static readonly MethodInfo NormalDistribution = typeof(alglib).GetMethod("normaldistribution", new[] { typeof(double) });
64    private static readonly MethodInfo ErrorFunction = typeof(alglib).GetMethod("errorfunction", new[] { typeof(double) });
65    private static readonly MethodInfo Bessel = typeof(alglib).GetMethod("besseli0", new[] { typeof(double) });
66    #endregion
67
68    public override bool CanChangeName { get { return false; } }
69    public override bool CanChangeDescription { get { return false; } }
70
71    #region parameter properties
72    public IFixedValueParameter<BoolValue> CheckExpressionsWithIntervalArithmeticParameter {
73      get { return (IFixedValueParameter<BoolValue>)Parameters[CheckExpressionsWithIntervalArithmeticParameterName]; }
74    }
75
76    public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter {
77      get { return (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
78    }
79    #endregion
80
81    #region properties
82    public bool CheckExpressionsWithIntervalArithmetic {
83      get { return CheckExpressionsWithIntervalArithmeticParameter.Value.Value; }
84      set { CheckExpressionsWithIntervalArithmeticParameter.Value.Value = value; }
85    }
86    public int EvaluatedSolutions {
87      get { return EvaluatedSolutionsParameter.Value.Value; }
88      set { EvaluatedSolutionsParameter.Value.Value = value; }
89    }
90    #endregion
91
92    public override IDeepCloneable Clone(Cloner cloner) {
93      return new SymbolicDataAnalysisExpressionCompiledTreeInterpreter(this, cloner);
94    }
95
96    private SymbolicDataAnalysisExpressionCompiledTreeInterpreter(SymbolicDataAnalysisExpressionCompiledTreeInterpreter original, Cloner cloner)
97      : base(original, cloner) {
98    }
99
100    [StorableConstructor]
101    private SymbolicDataAnalysisExpressionCompiledTreeInterpreter(StorableConstructorFlag _) : base(_) {
102    }
103
104    public SymbolicDataAnalysisExpressionCompiledTreeInterpreter() :
105      base("SymbolicDataAnalysisExpressionCompiledTreeInterpreter", "Interpreter which compiles the tree into a lambda") {
106      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, CheckExpressionsWithIntervalArithmeticParameterDescription, new BoolValue(false)));
107      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
108    }
109
110    public SymbolicDataAnalysisExpressionCompiledTreeInterpreter(string name, string description) :
111      base(name, description) {
112      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, CheckExpressionsWithIntervalArithmeticParameterDescription, new BoolValue(false)));
113      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
114    }
115
116    public void InitializeState() {
117      EvaluatedSolutions = 0;
118    }
119
120    public void ClearState() { }
121
122    private readonly object syncRoot = new object();
123    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows) {
124      if (CheckExpressionsWithIntervalArithmetic)
125        throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter.");
126
127      lock (syncRoot) {
128        EvaluatedSolutions++; // increment the evaluated solutions counter
129      }
130      var columns = dataset.DoubleVariables.Select(x => (IList<double>)dataset.GetReadOnlyDoubleValues(x)).ToArray();
131      var compiled = CompileTree(tree, dataset);
132      return rows.Select(x => compiled(x, columns));
133    }
134
135    public static Func<int, IList<double>[], double> CompileTree(ISymbolicExpressionTree tree, IDataset dataset) {
136      var lambda = CreateDelegate(tree, dataset);
137      return lambda.Compile();
138    }
139
140    public static Expression<Func<int, IList<double>[], double>> CreateDelegate(ISymbolicExpressionTree tree, IDataset dataset) {
141      var row = Expression.Parameter(typeof(int));
142      var columns = Expression.Parameter(typeof(IList<double>[]));
143      var variableIndices = dataset.DoubleVariables.Select((x, i) => new { x, i }).ToDictionary(e => e.x, e => e.i);
144      var expr = MakeExpr(tree, variableIndices, row, columns);
145      var lambda = Expression.Lambda<Func<int, IList<double>[], double>>(expr, row, columns);
146      return lambda;
147    }
148
149    private static Expression MakeExpr(ISymbolicExpressionTree tree, Dictionary<string, int> variableIndices, Expression row, Expression columns) {
150      var actualRoot = tree.Root.GetSubtree(0).GetSubtree(0);
151      return MakeExpr(actualRoot, variableIndices, row, columns);
152    }
153
154    private static readonly PropertyInfo Indexer = typeof(IList<double>).GetProperty("Item");
155    private static Expression MakeExpr(ISymbolicExpressionTreeNode node, Dictionary<string, int> variableIndices, Expression row, Expression columns) {
156      var opcode = OpCodes.MapSymbolToOpCode(node);
157      #region switch opcode
158      switch (opcode) {
159        case OpCodes.Constant: // fall through
160        case OpCodes.Number: {
161          var numberTreeNode = (INumericTreeNode)node;
162          return Expression.Constant(numberTreeNode.Value);
163          }
164        case OpCodes.Variable: {
165            var variableTreeNode = (VariableTreeNode)node;
166            var variableWeight = Expression.Constant(variableTreeNode.Weight);
167            var variableName = variableTreeNode.VariableName;
168            var indexExpr = Expression.Constant(variableIndices[variableName]);
169            var valuesExpr = Expression.ArrayIndex(columns, indexExpr);
170            return Expression.Multiply(variableWeight, Expression.Property(valuesExpr, Indexer, row));
171          }
172        case OpCodes.Add: {
173            Expression result = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
174            for (int i = 1; i < node.SubtreeCount; ++i) {
175              result = Expression.Add(result, MakeExpr(node.GetSubtree(i), variableIndices, row, columns));
176            }
177            return result;
178          }
179        case OpCodes.Sub: {
180            Expression result = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
181            if (node.SubtreeCount == 1)
182              return Expression.Negate(result);
183            for (int i = 1; i < node.SubtreeCount; ++i) {
184              result = Expression.Subtract(result, MakeExpr(node.GetSubtree(i), variableIndices, row, columns));
185            }
186            return result;
187          }
188        case OpCodes.Mul: {
189            Expression result = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
190            for (int i = 1; i < node.SubtreeCount; ++i) {
191              result = Expression.Multiply(result, MakeExpr(node.GetSubtree(i), variableIndices, row, columns));
192            }
193            return result;
194          }
195        case OpCodes.Div: {
196            Expression result = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
197            if (node.SubtreeCount == 1)
198              return Expression.Divide(Expression.Constant(1.0), result);
199            for (int i = 1; i < node.SubtreeCount; ++i) {
200              result = Expression.Divide(result, MakeExpr(node.GetSubtree(i), variableIndices, row, columns));
201            }
202            return result;
203          }
204        case OpCodes.Average: {
205            Expression result = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
206            for (int i = 1; i < node.SubtreeCount; ++i) {
207              result = Expression.Add(result, MakeExpr(node.GetSubtree(i), variableIndices, row, columns));
208            }
209            return Expression.Divide(result, Expression.Constant((double)node.SubtreeCount));
210          }
211        case OpCodes.Absolute: {
212            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
213            return Expression.Call(Abs, arg);
214          }
215        case OpCodes.Cos: {
216            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
217            return Expression.Call(Cos, arg);
218          }
219        case OpCodes.Sin: {
220            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
221            return Expression.Call(Sin, arg);
222          }
223        case OpCodes.Tan: {
224            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
225            return Expression.Call(Tan, arg);
226          }
227        case OpCodes.Tanh: {
228            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
229            return Expression.Call(Tanh, arg);
230          }
231        case OpCodes.Square: {
232            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
233            return Expression.Power(arg, Expression.Constant(2.0));
234          }
235        case OpCodes.Cube: {
236            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
237            return Expression.Power(arg, Expression.Constant(3.0));
238          }
239        case OpCodes.Power: {
240            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
241            var power = MakeExpr(node.GetSubtree(1), variableIndices, row, columns);
242            return Expression.Power(arg, Expression.Call(Round, power));
243          }
244        case OpCodes.SquareRoot: {
245            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
246            return Expression.Call(Sqrt, arg);
247          }
248        case OpCodes.CubeRoot: {
249            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
250            return Expression.Condition(Expression.LessThan(arg, Expression.Constant(0.0)),
251              Expression.Negate(Expression.Power(Expression.Negate(arg), Expression.Constant(1.0 / 3.0))),
252              Expression.Power(arg, Expression.Constant(1.0 / 3.0)));
253          }
254        case OpCodes.Root: {
255            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
256            var power = MakeExpr(node.GetSubtree(1), variableIndices, row, columns);
257            return Expression.Power(arg, Expression.Divide(Expression.Constant(1.0), Expression.Call(Round, power)));
258          }
259        case OpCodes.Exp: {
260            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
261            return Expression.Call(Exp, arg);
262          }
263        case OpCodes.Log: {
264            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
265            return Expression.Call(Log, arg);
266          }
267        case OpCodes.Gamma: {
268            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
269            var isNaN = Expression.Call(IsNaN, arg);
270
271            var result = Expression.Variable(typeof(double));
272            var expr = Expression.Block(
273              new[] { result },
274              Expression.IfThenElse(
275                isNaN,
276                Expression.Assign(result, Expression.Constant(double.NaN)),
277                Expression.Assign(result, Expression.Call(Gamma, arg))
278                ),
279              result
280              );
281            return expr;
282          }
283        case OpCodes.Psi: {
284            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
285            var isNaN = Expression.Call(IsNaN, arg);
286
287            var result = Expression.Variable(typeof(double));
288            var floor = Expression.Call(Floor, arg);
289            var expr = Expression.Block(
290              new[] { result },
291              Expression.IfThenElse(
292                isNaN,
293                Expression.Assign(result, Expression.Constant(double.NaN)),
294                Expression.IfThenElse(
295                  Expression.AndAlso(
296                    Expression.LessThanOrEqual(arg, Expression.Constant(0.0)),
297                    Expression.Call(IsAlmost, Expression.Subtract(floor, arg), Expression.Constant(0.0))),
298                  Expression.Assign(result, Expression.Constant(double.NaN)),
299                  Expression.Assign(result, Expression.Call(Psi, arg)))
300                ),
301              result);
302
303            return expr;
304          }
305        case OpCodes.Dawson: {
306            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
307            var isNaN = Expression.Call(IsNaN, arg);
308            var result = Expression.Variable(typeof(double));
309            var expr = Expression.Block(
310              new[] { result },
311              Expression.IfThenElse(isNaN,
312                Expression.Assign(result, Expression.Constant(double.NaN)),
313                Expression.Assign(result, Expression.Call(DawsonIntegral, arg))),
314              result
315              );
316
317            return expr;
318          }
319        case OpCodes.ExponentialIntegralEi: {
320            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
321            var isNaN = Expression.Call(IsNaN, arg);
322            var result = Expression.Variable(typeof(double));
323            var expr = Expression.Block(
324              new[] { result },
325              Expression.IfThenElse(isNaN,
326                Expression.Assign(result, Expression.Constant(double.NaN)),
327                Expression.Assign(result, Expression.Call(ExponentialIntegralEi, arg))),
328              result
329              );
330
331            return expr;
332          }
333        case OpCodes.SineIntegral: {
334            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
335            var isNaN = Expression.Call(IsNaN, arg);
336            var si = Expression.Variable(typeof(double));
337            var ci = Expression.Variable(typeof(double));
338            var block = Expression.Block(
339              new[] { si, ci },
340              Expression.Call(SineCosineIntegrals, arg, si, ci),
341              si
342              );
343            var result = Expression.Variable(typeof(double));
344            var expr = Expression.Block(new[] { result },
345              Expression.IfThenElse(isNaN,
346                Expression.Assign(result, Expression.Constant(double.NaN)),
347                Expression.Assign(result, block)),
348              result
349              );
350
351            return expr;
352          }
353        case OpCodes.CosineIntegral: {
354            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
355            var isNaN = Expression.Call(IsNaN, arg);
356            var si = Expression.Variable(typeof(double));
357            var ci = Expression.Variable(typeof(double));
358            var block = Expression.Block(
359              new[] { si, ci },
360              Expression.Call(SineCosineIntegrals, arg, si, ci),
361              ci
362              );
363            var result = Expression.Variable(typeof(double));
364            var expr = Expression.Block(new[] { result },
365              Expression.IfThenElse(isNaN,
366                Expression.Assign(result, Expression.Constant(double.NaN)),
367                Expression.Assign(result, block)),
368              result
369              );
370
371            return expr;
372          }
373        case OpCodes.HyperbolicSineIntegral: {
374            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
375            var isNaN = Expression.Call(IsNaN, arg);
376            var shi = Expression.Variable(typeof(double));
377            var chi = Expression.Variable(typeof(double));
378            var block = Expression.Block(
379              new[] { shi, chi },
380              Expression.Call(HyperbolicSineCosineIntegrals, arg, shi, chi),
381              shi
382              );
383            var result = Expression.Variable(typeof(double));
384            var expr = Expression.Block(new[] { result },
385              Expression.IfThenElse(isNaN,
386                Expression.Assign(result, Expression.Constant(double.NaN)),
387                Expression.Assign(result, block)),
388              result
389              );
390
391            return expr;
392          }
393        case OpCodes.HyperbolicCosineIntegral: {
394            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
395            var isNaN = Expression.Call(IsNaN, arg);
396            var shi = Expression.Variable(typeof(double));
397            var chi = Expression.Variable(typeof(double));
398            var block = Expression.Block(
399              new[] { shi, chi },
400              Expression.Call(HyperbolicSineCosineIntegrals, arg, shi, chi),
401              chi
402              );
403            var result = Expression.Variable(typeof(double));
404            var expr = Expression.Block(new[] { result },
405              Expression.IfThenElse(isNaN,
406                Expression.Assign(result, Expression.Constant(double.NaN)),
407                Expression.Assign(result, block)),
408              result
409              );
410
411            return expr;
412          }
413        case OpCodes.FresnelSineIntegral: {
414            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
415            var isNaN = Expression.Call(IsNaN, arg);
416            var s = Expression.Variable(typeof(double));
417            var c = Expression.Variable(typeof(double));
418            var block = Expression.Block(new[] { s, c }, Expression.Call(FresnelIntegral, arg, c, s), s);
419            var result = Expression.Variable(typeof(double));
420            var expr = Expression.Block(new[] { result },
421              Expression.IfThenElse(isNaN,
422                Expression.Assign(result, Expression.Constant(double.NaN)),
423                Expression.Assign(result, block)),
424              result
425              );
426
427            return expr;
428          }
429        case OpCodes.FresnelCosineIntegral: {
430            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
431            var isNaN = Expression.Call(IsNaN, arg);
432            var s = Expression.Variable(typeof(double));
433            var c = Expression.Variable(typeof(double));
434            var block = Expression.Block(new[] { s, c }, Expression.Call(FresnelIntegral, arg, c, s), c);
435            var result = Expression.Variable(typeof(double));
436            var expr = Expression.Block(new[] { result },
437              Expression.IfThenElse(isNaN,
438                Expression.Assign(result, Expression.Constant(double.NaN)),
439                Expression.Assign(result, block)),
440              result
441              );
442
443            return expr;
444          }
445        case OpCodes.AiryA: {
446            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
447            var isNaN = Expression.Call(IsNaN, arg);
448            var ai = Expression.Variable(typeof(double));
449            var aip = Expression.Variable(typeof(double));
450            var bi = Expression.Variable(typeof(double));
451            var bip = Expression.Variable(typeof(double));
452            var block = Expression.Block(new[] { ai, aip, bi, bip }, Expression.Call(Airy, arg, ai, aip, bi, bip), ai);
453            var result = Expression.Variable(typeof(double));
454            var expr = Expression.Block(new[] { result },
455              Expression.IfThenElse(isNaN,
456                Expression.Assign(result, Expression.Constant(double.NaN)),
457                Expression.Assign(result, block)),
458              result
459              );
460
461            return expr;
462          }
463        case OpCodes.AiryB: {
464            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
465            var isNaN = Expression.Call(IsNaN, arg);
466            var ai = Expression.Variable(typeof(double));
467            var aip = Expression.Variable(typeof(double));
468            var bi = Expression.Variable(typeof(double));
469            var bip = Expression.Variable(typeof(double));
470            var block = Expression.Block(new[] { ai, aip, bi, bip }, Expression.Call(Airy, arg, ai, aip, bi, bip), bi);
471            var result = Expression.Variable(typeof(double));
472            var expr = Expression.Block(new[] { result },
473              Expression.IfThenElse(isNaN,
474                Expression.Assign(result, Expression.Constant(double.NaN)),
475                Expression.Assign(result, block)),
476              result
477              );
478
479            return expr;
480          }
481        case OpCodes.Norm: {
482            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
483            var result = Expression.Variable(typeof(double));
484            return Expression.Block(
485              new[] { result },
486              Expression.IfThenElse(
487                Expression.Call(IsNaN, arg),
488                Expression.Assign(result, arg),
489                Expression.Assign(result, Expression.Call(NormalDistribution, arg))),
490              result);
491          }
492        case OpCodes.Erf: {
493            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
494            var isNaN = Expression.Call(IsNaN, arg);
495            var result = Expression.Variable(typeof(double));
496            return Expression.Block(
497              new[] { result },
498              Expression.IfThenElse(
499                isNaN,
500                Expression.Assign(result, Expression.Constant(double.NaN)),
501                Expression.Assign(result, Expression.Call(ErrorFunction, arg))),
502              result);
503          }
504        case OpCodes.Bessel: {
505            var arg = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
506            var isNaN = Expression.Call(IsNaN, arg);
507            var result = Expression.Variable(typeof(double));
508            return Expression.Block(
509              new[] { result },
510              Expression.IfThenElse(
511                isNaN,
512                Expression.Assign(result, Expression.Constant(double.NaN)),
513                Expression.Assign(result, Expression.Call(Bessel, arg))),
514              result);
515          }
516        case OpCodes.AnalyticQuotient: {
517            var x1 = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
518            var x2 = MakeExpr(node.GetSubtree(1), variableIndices, row, columns);
519            return Expression.Divide(x1,
520              Expression.Call(Sqrt,
521              Expression.Add(
522                Expression.Constant(1.0),
523                Expression.Multiply(x2, x2))));
524          }
525        case OpCodes.IfThenElse: {
526            var test = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
527            var result = Expression.Variable(typeof(double));
528            var condition = Expression.IfThenElse(Expression.GreaterThan(test, Expression.Constant(0.0)),
529              Expression.Assign(result, MakeExpr(node.GetSubtree(1), variableIndices, row, columns)),
530              Expression.Assign(result, MakeExpr(node.GetSubtree(2), variableIndices, row, columns)));
531            return Expression.Block(new[] { result }, condition, result);
532          }
533        case OpCodes.AND: {
534            var result = Expression.Variable(typeof(double));
535            var expr = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
536
537            for (int i = 1; i < node.SubtreeCount; ++i) {
538              expr = Expression.Block(new[] { result },
539                Expression.IfThenElse(
540                  Expression.GreaterThan(expr, Expression.Constant(0.0)),
541                  Expression.Assign(result, MakeExpr(node.GetSubtree(i), variableIndices, row, columns)),
542                  Expression.Assign(result, expr)),
543                result
544                );
545            }
546
547            return Expression.Block(
548              new[] { result },
549              Expression.Assign(result, expr),
550              Expression.IfThenElse(
551                Expression.GreaterThan(result, Expression.Constant(0.0)),
552                Expression.Assign(result, Expression.Constant(1.0)),
553                Expression.Assign(result, Expression.Constant(-1.0))
554                ),
555              result
556              );
557          }
558        case OpCodes.OR: {
559            var result = Expression.Variable(typeof(double));
560            var expr = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
561
562            for (int i = 1; i < node.SubtreeCount; ++i) {
563              expr = Expression.Block(new[] { result },
564                Expression.IfThenElse(
565                  Expression.LessThanOrEqual(expr, Expression.Constant(0.0)),
566                  Expression.Assign(result, MakeExpr(node.GetSubtree(i), variableIndices, row, columns)),
567                  Expression.Assign(result, expr)),
568                result
569                );
570            }
571
572            return Expression.Block(
573              new[] { result },
574              Expression.Assign(result, expr),
575              Expression.IfThenElse(
576                Expression.GreaterThan(result, Expression.Constant(0.0)),
577                Expression.Assign(result, Expression.Constant(1.0)),
578                Expression.Assign(result, Expression.Constant(-1.0))
579                ),
580              result
581              );
582          }
583        case OpCodes.NOT: {
584            var value = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
585            var result = Expression.Variable(typeof(double));
586            var condition = Expression.IfThenElse(Expression.GreaterThan(value, Expression.Constant(0.0)),
587              Expression.Assign(result, Expression.Constant(-1.0)),
588              Expression.Assign(result, Expression.Constant(1.0)));
589            return Expression.Block(new[] { result }, condition, result);
590          }
591        case OpCodes.XOR: {
592            var ps = Expression.Variable(typeof(int));
593            var block = Expression.Block(
594              new[] { ps },
595              Expression.Assign(ps, Expression.Constant(0)),
596              ps
597              );
598
599            foreach (var subtree in node.Subtrees) {
600              var expr = MakeExpr(subtree, variableIndices, row, columns);
601              block = Expression.Block(
602                new[] { ps },
603                Expression.Assign(ps, block),
604                Expression.IfThen(Expression.GreaterThan(expr, Expression.Constant(0.0)),
605                  Expression.PostIncrementAssign(ps)),
606                ps
607                );
608            }
609
610            var result = Expression.Variable(typeof(double));
611            var xorExpr = Expression.Block(
612              new[] { result },
613              Expression.IfThenElse(
614                Expression.Equal(Expression.Modulo(block, Expression.Constant(2)), Expression.Constant(0)),
615                Expression.Assign(result, Expression.Constant(-1.0)),
616                Expression.Assign(result, Expression.Constant(1.0))
617                ),
618              result
619              );
620            return xorExpr;
621          }
622        case OpCodes.GT: {
623            var left = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
624            var right = MakeExpr(node.GetSubtree(1), variableIndices, row, columns);
625            var result = Expression.Variable(typeof(double));
626
627            var condition = Expression.IfThenElse(Expression.GreaterThan(left, right),
628              Expression.Assign(result, Expression.Constant(1.0)), Expression.Assign(result, Expression.Constant(-1.0)));
629            return Expression.Block(
630              new[] { result },
631              condition,
632              result);
633          }
634        case OpCodes.LT: {
635            var left = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
636            var right = MakeExpr(node.GetSubtree(1), variableIndices, row, columns);
637            var result = Expression.Variable(typeof(double));
638
639            var condition = Expression.IfThenElse(Expression.LessThan(left, right),
640              Expression.Assign(result, Expression.Constant(1.0)), Expression.Assign(result, Expression.Constant(-1.0)));
641            return Expression.Block(new[] { result }, condition, result);
642          }
643        case OpCodes.VariableCondition: {
644            var variableConditionTreeNode = (VariableConditionTreeNode)node;
645            if (variableConditionTreeNode.Symbol.IgnoreSlope) throw new NotSupportedException("Strict variable conditionals are not supported");
646            var variableName = variableConditionTreeNode.VariableName;
647            var indexExpr = Expression.Constant(variableIndices[variableName]);
648            var valuesExpr = Expression.ArrayIndex(columns, indexExpr);
649            var variableValue = Expression.Property(valuesExpr, Indexer, row);
650            var variableThreshold = Expression.Constant(variableConditionTreeNode.Threshold);
651            var variableSlope = Expression.Constant(variableConditionTreeNode.Slope);
652
653            var x = Expression.Subtract(variableValue, variableThreshold);
654            var xSlope = Expression.Multiply(Expression.Negate(variableSlope), x);
655            var xSlopeExp = Expression.Call(Exp, xSlope);
656            var p = Expression.Divide(Expression.Constant(1), Expression.Add(Expression.Constant(1), xSlopeExp));
657            var trueBranch = MakeExpr(node.GetSubtree(0), variableIndices, row, columns);
658            var falseBranch = MakeExpr(node.GetSubtree(1), variableIndices, row, columns);
659            return Expression.Add(
660              Expression.Multiply(trueBranch, p),
661              Expression.Multiply(falseBranch, Expression.Subtract(Expression.Constant(1), p))
662              );
663          }
664        default:
665          throw new NotSupportedException("Unsupported symbol: " + node.Symbol);
666      }
667      #endregion
668    }
669  }
670}
Note: See TracBrowser for help on using the repository browser.