Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2789_MathNetNumerics-Exploration/HeuristicLab.Algorithms.DataAnalysis.Experimental/TreeToDiffSharpConverter.cs @ 16189

Last change on this file since 16189 was 15322, checked in by gkronber, 7 years ago

#2789 worked on NLR with constraints

File size: 16.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Runtime.Serialization;
26using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
27using HeuristicLab.Problems.DataAnalysis.Symbolic;
28using DiffSharp.Interop.Float64;
29using System.Linq.Expressions;
30using System.Reflection;
31
32namespace HeuristicLab.Algorithms.DataAnalysis.Experimental {
33  public class TreeToDiffSharpConverter {
34    public delegate double ParametricFunction(double[] vars);
35
36    public delegate Tuple<double[], double> ParametricFunctionGradient(double[] vars);
37
38    #region helper class
39    public class DataForVariable {
40      public readonly string variableName;
41      public readonly string variableValue; // for factor vars
42      public readonly int lag;
43
44      public DataForVariable(string varName, string varValue, int lag) {
45        this.variableName = varName;
46        this.variableValue = varValue;
47        this.lag = lag;
48      }
49
50      public override bool Equals(object obj) {
51        var other = obj as DataForVariable;
52        if (other == null) return false;
53        return other.variableName.Equals(this.variableName) &&
54               other.variableValue.Equals(this.variableValue) &&
55               other.lag == this.lag;
56      }
57
58      public override int GetHashCode() {
59        return variableName.GetHashCode() ^ variableValue.GetHashCode() ^ lag;
60      }
61    }
62    #endregion
63
64
65    public static bool TryConvertToDiffSharp(ISymbolicExpressionTree tree, bool makeVariableWeightsVariable,
66      out List<DataForVariable> parameters, out double[] initialConstants,
67      out Func<DV, D> func) {
68
69      // use a transformator object which holds the state (variable list, parameter list, ...) for recursive transformation of the tree
70      var transformator = new TreeToDiffSharpConverter(makeVariableWeightsVariable);
71      try {
72
73        // the list of variable names represents the names for dv[0] ... dv[d-1] where d is the number of input variables
74        // the remaining entries of d represent the parameter values
75        transformator.ExtractParameters(tree.Root.GetSubtree(0));
76
77        var lambda = transformator.CreateDelegate(tree, transformator.parameters);
78        func = lambda.Compile();
79
80        var parameterEntries = transformator.parameters.ToArray(); // guarantee same order for keys and values
81        parameters = new List<DataForVariable>(parameterEntries.Select(kvp => kvp.Key));
82        initialConstants = transformator.initialConstants.ToArray();
83        return true;
84      } catch (ConversionException) {
85        func = null;
86        parameters = null;
87        initialConstants = null;
88      }
89      return false;
90    }
91
92    public Expression<Func<DV, D>> CreateDelegate(ISymbolicExpressionTree tree, Dictionary<DataForVariable, int> parameters) {
93      paramIdx = parameters.Count; // first non-variable parameter
94      var dv = Expression.Parameter(typeof(DV));
95      var expr = MakeExpr(tree.Root.GetSubtree(0), parameters, dv);
96      var lambda = Expression.Lambda<Func<DV, D>>(expr, dv);
97      return lambda;
98    }
99
100    // state for recursive transformation of trees
101    private readonly List<double> initialConstants;
102    private readonly Dictionary<DataForVariable, int> parameters;
103    private readonly bool makeVariableWeightsVariable;
104    private int paramIdx;
105
106    private TreeToDiffSharpConverter(bool makeVariableWeightsVariable) {
107      this.makeVariableWeightsVariable = makeVariableWeightsVariable;
108      this.initialConstants = new List<double>();
109      this.parameters = new Dictionary<DataForVariable, int>();
110    }
111
112    private void ExtractParameters(ISymbolicExpressionTreeNode node) {
113      if (node.Symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Constant) {
114        initialConstants.Add(((ConstantTreeNode)node).Value);
115      } else if (node.Symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Variable || node.Symbol is BinaryFactorVariable) {
116        var varNode = node as VariableTreeNodeBase;
117        var factorVarNode = node as BinaryFactorVariableTreeNode;
118        // factor variable values are only 0 or 1 and set in x accordingly
119        var varValue = factorVarNode != null ? factorVarNode.VariableValue : string.Empty;
120        FindOrCreateParameter(parameters, varNode.VariableName, varValue);
121
122        if (makeVariableWeightsVariable) {
123          initialConstants.Add(varNode.Weight);
124        }
125      } else if (node.Symbol is FactorVariable) {
126        var factorVarNode = node as FactorVariableTreeNode;
127        var products = new List<D>();
128        foreach (var variableValue in factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName)) {
129          FindOrCreateParameter(parameters, factorVarNode.VariableName, variableValue);
130
131          initialConstants.Add(factorVarNode.GetValue(variableValue));
132        }
133      } else if (node.Symbol is LaggedVariable) {
134        var varNode = node as LaggedVariableTreeNode;
135        FindOrCreateParameter(parameters, varNode.VariableName, string.Empty, varNode.Lag);
136
137        if (makeVariableWeightsVariable) {
138          initialConstants.Add(varNode.Weight);
139        }
140      } else if (node.Symbol is Addition) {
141        foreach (var subTree in node.Subtrees) {
142          ExtractParameters(subTree);
143        }
144      } else if (node.Symbol is Subtraction) {
145        for (int i = 0; i < node.SubtreeCount; i++) {
146          ExtractParameters(node.GetSubtree(i));
147        }
148      } else if (node.Symbol is Multiplication) {
149        foreach (var subTree in node.Subtrees) {
150          ExtractParameters(subTree);
151        }
152      } else if (node.Symbol is Division) {
153        foreach (var subTree in node.Subtrees) {
154          ExtractParameters(subTree);
155        }
156      } else if (node.Symbol is Logarithm) {
157        ExtractParameters(node.GetSubtree(0));
158      } else if (node.Symbol is Exponential) {
159        ExtractParameters(node.GetSubtree(0));
160      } else if (node.Symbol is Square) {
161        ExtractParameters(node.GetSubtree(0));
162      } else if (node.Symbol is SquareRoot) {
163        ExtractParameters(node.GetSubtree(0));
164      } else if (node.Symbol is Sine) {
165        ExtractParameters(node.GetSubtree(0));
166      } else if (node.Symbol is Cosine) {
167        ExtractParameters(node.GetSubtree(0));
168      } else if (node.Symbol is Tangent) {
169        ExtractParameters(node.GetSubtree(0));
170      } else if (node.Symbol is StartSymbol) {
171        ExtractParameters(node.GetSubtree(0));
172      } else throw new ConversionException();
173    }
174
175    private Func<DV, D> CreateDiffSharpFunc(ISymbolicExpressionTreeNode node, Dictionary<DataForVariable, int> parameters) {
176      this.paramIdx = parameters.Count; // first idx of non-variable parameter     
177      var f = CreateDiffSharpFunc(node, parameters);
178      return (DV paramValues) => f(paramValues);
179    }
180
181    private static readonly MethodInfo DvIndexer = typeof(DV).GetMethod("get_Item", new[] { typeof(int) });
182    private static readonly MethodInfo d_Add_d = typeof(D).GetMethod("op_Addition", new[] { typeof(D), typeof(D) });
183    private static readonly MethodInfo d_Neg = typeof(D).GetMethod("Neg", new[] { typeof(D) });
184    private static readonly MethodInfo d_Mul_d = typeof(D).GetMethod("op_Multiply", new[] { typeof(D), typeof(D) });
185    private static readonly MethodInfo d_Mul_f = typeof(D).GetMethod("op_Multiply", new[] { typeof(D), typeof(double) });
186    private static readonly MethodInfo d_Div_d = typeof(D).GetMethod("op_Division", new[] { typeof(D), typeof(D) });
187    private static readonly MethodInfo f_Div_d = typeof(D).GetMethod("op_Division", new[] { typeof(double), typeof(D) });
188    private static readonly MethodInfo d_Sub_d = typeof(D).GetMethod("op_Subtraction", new[] { typeof(D), typeof(D) });
189    private static readonly MethodInfo d_Pow_f = typeof(D).GetMethod("Pow", new[] { typeof(D), typeof(double) });
190    private static readonly MethodInfo d_Log = typeof(D).GetMethod("Log", new[] { typeof(D) });
191    private static readonly MethodInfo d_Exp = typeof(D).GetMethod("Exp", new[] { typeof(D) });
192
193
194
195    private Expression MakeExpr(ISymbolicExpressionTreeNode node, Dictionary<DataForVariable, int> parameters, ParameterExpression dv) {
196      if (node.Symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Constant) {
197        return Expression.Call(dv, DvIndexer, Expression.Constant(paramIdx++));
198      }
199      if (node.Symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Variable || node.Symbol is BinaryFactorVariable) {
200        var varNode = node as VariableTreeNodeBase;
201        var factorVarNode = node as BinaryFactorVariableTreeNode;
202        // factor variable values are only 0 or 1 and set in x accordingly
203        var varValue = factorVarNode != null ? factorVarNode.VariableValue : string.Empty;
204        var par = FindOrCreateParameter(parameters, varNode.VariableName, varValue);
205
206        if (makeVariableWeightsVariable) {
207          var w = Expression.Call(dv, DvIndexer, Expression.Constant(paramIdx++));
208          var v = Expression.Call(dv, DvIndexer, Expression.Constant(par));
209          return Expression.Call(d_Mul_d, w, v);
210        } else {
211          var w = Expression.Constant(varNode.Weight);
212          var v = Expression.Call(dv, DvIndexer, Expression.Constant(par));
213          return Expression.Call(d_Mul_f, v, w);
214        }
215      }
216      if (node.Symbol is FactorVariable) {
217        var factorVarNode = node as FactorVariableTreeNode;
218        var products = new List<D>();
219        var firstValue = factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName).First();
220        var parForFirstValue = FindOrCreateParameter(parameters, factorVarNode.VariableName, firstValue);
221        var weightForFirstValue = Expression.Call(dv, DvIndexer, Expression.Constant(paramIdx++));
222        var valForFirstValue = Expression.Call(dv, DvIndexer, Expression.Constant(parForFirstValue));
223        var res = Expression.Call(d_Mul_d, weightForFirstValue, valForFirstValue);
224
225        foreach (var variableValue in factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName).Skip(1)) {
226          var par = FindOrCreateParameter(parameters, factorVarNode.VariableName, variableValue);
227     
228          var weight = Expression.Call(dv, DvIndexer, Expression.Constant(paramIdx++));
229          var v = Expression.Call(dv, DvIndexer, Expression.Constant(par));
230
231          res = Expression.Call(d_Add_d, res, Expression.Call(d_Mul_d, weight, v));
232        }
233        return res;
234      }
235      // if (node.Symbol is LaggedVariable) {
236      //   var varNode = node as LaggedVariableTreeNode;
237      //   var par = FindOrCreateParameter(parameters, varNode.VariableName, string.Empty, varNode.Lag);
238      //
239      //   if (makeVariableWeightsVariable) {
240      //     initialConstants.Add(varNode.Weight);
241      //     var w = paramValues[paramIdx++];
242      //     return w * paramValues[par];
243      //   } else {
244      //     return varNode.Weight * paramValues[par];
245      //   }
246      // }
247      if (node.Symbol is Addition) {
248        var f = MakeExpr(node.Subtrees.First(), parameters, dv);
249
250        foreach (var subTree in node.Subtrees.Skip(1)) {
251          f = Expression.Call(d_Add_d, f, MakeExpr(subTree, parameters, dv));
252        }
253        return f;
254      }
255      if (node.Symbol is Subtraction) {
256        if (node.SubtreeCount == 1) {
257          return Expression.Call(d_Neg, MakeExpr(node.Subtrees.First(), parameters, dv));
258        } else {
259          var f = MakeExpr(node.Subtrees.First(), parameters, dv);
260
261          foreach (var subTree in node.Subtrees.Skip(1)) {
262            f = Expression.Call(d_Sub_d, f, MakeExpr(subTree, parameters, dv));
263          }
264          return f;
265        }
266      }
267      if (node.Symbol is Multiplication) {
268        var f = MakeExpr(node.Subtrees.First(), parameters, dv);
269        foreach (var subTree in node.Subtrees.Skip(1)) {
270          f = Expression.Call(d_Mul_d, f, MakeExpr(subTree, parameters, dv));
271        }
272        return f;
273      }
274      if (node.Symbol is Division) {
275        if (node.SubtreeCount == 1) {
276          return Expression.Call(f_Div_d, Expression.Constant(1.0), MakeExpr(node.Subtrees.First(), parameters, dv));
277        } else {
278          var f = MakeExpr(node.Subtrees.First(), parameters, dv);
279
280          foreach (var subTree in node.Subtrees.Skip(1)) {
281            f = Expression.Call(d_Div_d, f, MakeExpr(subTree, parameters, dv));
282          }
283          return f;
284        }
285      }
286      if (node.Symbol is Logarithm) {
287        return Expression.Call(d_Log, MakeExpr(node.GetSubtree(0), parameters, dv));
288      }
289      if (node.Symbol is Exponential) {
290        return Expression.Call(d_Exp, MakeExpr(node.GetSubtree(0), parameters, dv));
291      }
292      if (node.Symbol is Square) {
293        return Expression.Call(d_Pow_f, MakeExpr(node.GetSubtree(0), parameters, dv), Expression.Constant(2.0));
294      }
295      if (node.Symbol is SquareRoot) {
296        return Expression.Call(d_Pow_f, MakeExpr(node.GetSubtree(0), parameters, dv), Expression.Constant(0.5));
297      }
298      // if (node.Symbol is Sine) {
299      //   return AD.Sin(CreateDiffSharpFunc(node.GetSubtree(0), parameters, paramValues));
300      // }
301      // if (node.Symbol is Cosine) {
302      //   return AD.Cos(CreateDiffSharpFunc(node.GetSubtree(0), parameters, paramValues));
303      // }
304      // if (node.Symbol is Tangent) {
305      //   return AD.Tan(CreateDiffSharpFunc(node.GetSubtree(0), parameters, paramValues));
306      // }
307      if (node.Symbol is StartSymbol) {
308        //var alpha = Expression.Call(dv, DvIndexer, Expression.Constant(paramIdx++));
309        //var beta = Expression.Call(dv, DvIndexer, Expression.Constant(paramIdx++));
310
311        // return Expression.Call(d_Add_d, beta,
312        //   Expression.Call(d_Mul_d, alpha, MakeExpr(node.GetSubtree(0), parameters, dv)));
313        return MakeExpr(node.GetSubtree(0), parameters, dv);
314      }
315      throw new ConversionException();
316    }
317
318
319    // for each factor variable value we need a parameter which represents a binary indicator for that variable & value combination
320    // each binary indicator is only necessary once. So we only create a parameter if this combination is not yet available.
321    private static int FindOrCreateParameter(Dictionary<DataForVariable, int> parameters,
322      string varName, string varValue = "", int lag = 0) {
323      var data = new DataForVariable(varName, varValue, lag);
324      int idx = -1;
325      if (parameters.TryGetValue(data, out idx)) return idx;
326      else parameters[data] = parameters.Count;
327      return idx;
328    }
329
330    public static bool IsCompatible(ISymbolicExpressionTree tree) {
331      var containsUnknownSymbol = (
332        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
333        where
334          !(n.Symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Variable) &&
335          !(n.Symbol is BinaryFactorVariable) &&
336          !(n.Symbol is FactorVariable) &&
337          !(n.Symbol is LaggedVariable) &&
338          !(n.Symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Constant) &&
339          !(n.Symbol is Addition) &&
340          !(n.Symbol is Subtraction) &&
341          !(n.Symbol is Multiplication) &&
342          !(n.Symbol is Division) &&
343          !(n.Symbol is Logarithm) &&
344          !(n.Symbol is Exponential) &&
345          !(n.Symbol is SquareRoot) &&
346          !(n.Symbol is Square) &&
347          !(n.Symbol is Sine) &&
348          !(n.Symbol is Cosine) &&
349          !(n.Symbol is Tangent) &&
350          !(n.Symbol is StartSymbol)
351        select n).Any();
352      return !containsUnknownSymbol;
353    }
354    #region exception class
355    [Serializable]
356    public class ConversionException : Exception {
357
358      public ConversionException() {
359      }
360
361      public ConversionException(string message) : base(message) {
362      }
363
364      public ConversionException(string message, Exception inner) : base(message, inner) {
365      }
366
367      protected ConversionException(
368        SerializationInfo info,
369        StreamingContext context) : base(info, context) {
370      }
371    }
372    #endregion
373  }
374}
Note: See TracBrowser for help on using the repository browser.