Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2974_Constants_Optimization/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Converters/TreeToAutoDiffTermConverter.cs @ 16461

Last change on this file since 16461 was 16461, checked in by mkommend, 5 years ago

#2974: Added unit tests and refactoring.

File size: 15.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.Linq;
25using System.Runtime.Serialization;
26using AutoDiff;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28
29namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
30  public class TreeToAutoDiffTermConverter {
31    public delegate double ParametricFunction(double[] vars, double[] @params);
32
33    public delegate Tuple<double[], double> ParametricFunctionGradient(double[] vars, double[] @params);
34
35    #region helper class
36    public class DataForVariable {
37      public readonly string variableName;
38      public readonly string variableValue; // for factor vars
39      public readonly int lag;
40
41      public DataForVariable(string varName, string varValue, int lag) {
42        this.variableName = varName;
43        this.variableValue = varValue;
44        this.lag = lag;
45      }
46
47      public override bool Equals(object obj) {
48        var other = obj as DataForVariable;
49        if (other == null) return false;
50        return other.variableName.Equals(this.variableName) &&
51               other.variableValue.Equals(this.variableValue) &&
52               other.lag == this.lag;
53      }
54
55      public override int GetHashCode() {
56        return variableName.GetHashCode() ^ variableValue.GetHashCode() ^ lag;
57      }
58    }
59    #endregion
60
61    #region derivations of functions
62    // create function factory for arctangent
63    private static readonly Func<Term, UnaryFunc> arctan = UnaryFunc.Factory(
64      eval: Math.Atan,
65      diff: x => 1 / (1 + x * x));
66
67    private static readonly Func<Term, UnaryFunc> sin = UnaryFunc.Factory(
68      eval: Math.Sin,
69      diff: Math.Cos);
70
71    private static readonly Func<Term, UnaryFunc> cos = UnaryFunc.Factory(
72      eval: Math.Cos,
73      diff: x => -Math.Sin(x));
74
75    private static readonly Func<Term, UnaryFunc> tan = UnaryFunc.Factory(
76      eval: Math.Tan,
77      diff: x => 1 + Math.Tan(x) * Math.Tan(x));
78
79    private static readonly Func<Term, UnaryFunc> erf = UnaryFunc.Factory(
80      eval: alglib.errorfunction,
81      diff: x => 2.0 * Math.Exp(-(x * x)) / Math.Sqrt(Math.PI));
82
83    private static readonly Func<Term, UnaryFunc> norm = UnaryFunc.Factory(
84      eval: alglib.normaldistribution,
85      diff: x => -(Math.Exp(-(x * x)) * Math.Sqrt(Math.Exp(x * x)) * x) / Math.Sqrt(2 * Math.PI));
86
87    private static readonly Func<Term, UnaryFunc> abs = UnaryFunc.Factory(
88      eval: Math.Abs,
89      diff: x => Math.Sign(x)
90      );
91
92    #endregion
93
94    public static bool TryConvertToAutoDiff(ISymbolicExpressionTree tree, bool makeVariableWeightsVariable, bool addLinearScalingTerms,
95      out List<DataForVariable> parameters, out double[] initialConstants,
96      out ParametricFunction func,
97      out ParametricFunctionGradient func_grad) {
98
99      // use a transformator object which holds the state (variable list, parameter list, ...) for recursive transformation of the tree
100      var transformator = new TreeToAutoDiffTermConverter(makeVariableWeightsVariable);
101      AutoDiff.Term term;
102      try {
103        term = transformator.ConvertToAutoDiff(tree.Root.GetSubtree(0));
104
105        if (addLinearScalingTerms) {
106          // scaling variables α, β are given at the beginning of the parameter vector
107          var alpha = new AutoDiff.Variable();
108          var beta = new AutoDiff.Variable();
109          transformator.variables.Insert(0, alpha);
110          transformator.variables.Insert(0, beta);
111
112          term = term * alpha + beta;
113        }
114
115        var parameterEntries = transformator.parameters.ToArray(); // guarantee same order for keys and values
116        var compiledTerm = term.Compile(transformator.variables.ToArray(),
117          parameterEntries.Select(kvp => kvp.Value).ToArray());
118
119        parameters = new List<DataForVariable>(parameterEntries.Select(kvp => kvp.Key));
120        initialConstants = transformator.initialConstants.ToArray();
121        func = (vars, @params) => compiledTerm.Evaluate(vars, @params);
122        func_grad = (vars, @params) => compiledTerm.Differentiate(vars, @params);
123        return true;
124      } catch (ConversionException) {
125        parameters = null;
126        initialConstants = null;
127        func = null;
128        func_grad = null;
129      }
130      return false;
131    }
132
133    public static bool TryConvertToAutoDiff(ISymbolicExpressionTree tree, bool makeVariableWeightsVariable, bool addLinearScalingTerms, Dictionary<DataForVariable, AutoDiff.Variable> parameters,
134      out ParametricFunction func,
135      out ParametricFunctionGradient func_grad
136  ) {
137
138      // use a transformator object which holds the state (variable list, parameter list, ...) for recursive transformation of the tree
139      var transformator = new TreeToAutoDiffTermConverter(makeVariableWeightsVariable, parameters);
140      AutoDiff.Term term;
141      try {
142        term = transformator.ConvertToAutoDiff(tree.Root.GetSubtree(0));
143
144        if (addLinearScalingTerms) {
145          // scaling variables α, β are given at the beginning of the parameter vector
146          var alpha = new AutoDiff.Variable();
147          var beta = new AutoDiff.Variable();
148          transformator.variables.Insert(0, alpha);
149          transformator.variables.Insert(0, beta);
150
151          term = term * alpha + beta;
152        }
153       
154        var compiledTerm = term.Compile(transformator.variables.ToArray(), parameters.Select(kvp => kvp.Value).ToArray());
155
156
157        func = (vars, @params) => compiledTerm.Evaluate(vars, @params);
158        func_grad = (vars, @params) => compiledTerm.Differentiate(vars, @params);
159        return true;
160      } catch (ConversionException) {
161        func = null;
162        func_grad = null;
163      }
164      return false;
165    }
166
167    // state for recursive transformation of trees
168    private readonly List<double> initialConstants;
169    private readonly Dictionary<DataForVariable, AutoDiff.Variable> parameters;
170    private readonly List<AutoDiff.Variable> variables;
171    private readonly bool makeVariableWeightsVariable;
172
173    private TreeToAutoDiffTermConverter(bool makeVariableWeightsVariable, Dictionary<DataForVariable, AutoDiff.Variable> parameters = null) {
174      this.makeVariableWeightsVariable = makeVariableWeightsVariable;
175      this.initialConstants = new List<double>();
176      if (parameters == null)
177        this.parameters = new Dictionary<DataForVariable, AutoDiff.Variable>();
178      else
179        this.parameters = parameters;
180      this.variables = new List<AutoDiff.Variable>();
181    }
182
183    private AutoDiff.Term ConvertToAutoDiff(ISymbolicExpressionTreeNode node) {
184      if (node.Symbol is Constant) {
185        initialConstants.Add(((ConstantTreeNode)node).Value);
186        var var = new AutoDiff.Variable();
187        variables.Add(var);
188        return var;
189      }
190      if (node.Symbol is Variable || node.Symbol is BinaryFactorVariable) {
191        var varNode = node as VariableTreeNodeBase;
192        var factorVarNode = node as BinaryFactorVariableTreeNode;
193        // factor variable values are only 0 or 1 and set in x accordingly
194        var varValue = factorVarNode != null ? factorVarNode.VariableValue : string.Empty;
195        var par = FindOrCreateParameter(parameters, varNode.VariableName, varValue);
196
197        if (makeVariableWeightsVariable) {
198          initialConstants.Add(varNode.Weight);
199          var w = new AutoDiff.Variable();
200          variables.Add(w);
201          return AutoDiff.TermBuilder.Product(w, par);
202        } else {
203          return varNode.Weight * par;
204        }
205      }
206      if (node.Symbol is FactorVariable) {
207        var factorVarNode = node as FactorVariableTreeNode;
208        var products = new List<Term>();
209        foreach (var variableValue in factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName)) {
210          var par = FindOrCreateParameter(parameters, factorVarNode.VariableName, variableValue);
211
212          initialConstants.Add(factorVarNode.GetValue(variableValue));
213          var wVar = new AutoDiff.Variable();
214          variables.Add(wVar);
215
216          products.Add(AutoDiff.TermBuilder.Product(wVar, par));
217        }
218        return AutoDiff.TermBuilder.Sum(products);
219      }
220      if (node.Symbol is LaggedVariable) {
221        var varNode = node as LaggedVariableTreeNode;
222        var par = FindOrCreateParameter(parameters, varNode.VariableName, string.Empty, varNode.Lag);
223
224        if (makeVariableWeightsVariable) {
225          initialConstants.Add(varNode.Weight);
226          var w = new AutoDiff.Variable();
227          variables.Add(w);
228          return AutoDiff.TermBuilder.Product(w, par);
229        } else {
230          return varNode.Weight * par;
231        }
232      }
233      if (node.Symbol is Addition) {
234        List<AutoDiff.Term> terms = new List<Term>();
235        foreach (var subTree in node.Subtrees) {
236          terms.Add(ConvertToAutoDiff(subTree));
237        }
238        return AutoDiff.TermBuilder.Sum(terms);
239      }
240      if (node.Symbol is Subtraction) {
241        List<AutoDiff.Term> terms = new List<Term>();
242        for (int i = 0; i < node.SubtreeCount; i++) {
243          AutoDiff.Term t = ConvertToAutoDiff(node.GetSubtree(i));
244          if (i > 0) t = -t;
245          terms.Add(t);
246        }
247        if (terms.Count == 1) return -terms[0];
248        else return AutoDiff.TermBuilder.Sum(terms);
249      }
250      if (node.Symbol is Multiplication) {
251        List<AutoDiff.Term> terms = new List<Term>();
252        foreach (var subTree in node.Subtrees) {
253          terms.Add(ConvertToAutoDiff(subTree));
254        }
255        if (terms.Count == 1) return terms[0];
256        else return terms.Aggregate((a, b) => new AutoDiff.Product(a, b));
257      }
258      if (node.Symbol is Division) {
259        List<AutoDiff.Term> terms = new List<Term>();
260        foreach (var subTree in node.Subtrees) {
261          terms.Add(ConvertToAutoDiff(subTree));
262        }
263        if (terms.Count == 1) return 1.0 / terms[0];
264        else return terms.Aggregate((a, b) => new AutoDiff.Product(a, 1.0 / b));
265      }
266      if (node.Symbol is Absolute) {
267        var x1 = ConvertToAutoDiff(node.GetSubtree(0));
268        return abs(x1);
269      }
270      if (node.Symbol is AnalyticQuotient) {
271        var x1 = ConvertToAutoDiff(node.GetSubtree(0));
272        var x2 = ConvertToAutoDiff(node.GetSubtree(1));
273        return x1 / (TermBuilder.Power(1 + x2 * x2, 0.5));
274      }
275      if (node.Symbol is Logarithm) {
276        return AutoDiff.TermBuilder.Log(
277          ConvertToAutoDiff(node.GetSubtree(0)));
278      }
279      if (node.Symbol is Exponential) {
280        return AutoDiff.TermBuilder.Exp(
281          ConvertToAutoDiff(node.GetSubtree(0)));
282      }
283      if (node.Symbol is Square) {
284        return AutoDiff.TermBuilder.Power(
285          ConvertToAutoDiff(node.GetSubtree(0)), 2.0);
286      }
287      if (node.Symbol is SquareRoot) {
288        return AutoDiff.TermBuilder.Power(
289          ConvertToAutoDiff(node.GetSubtree(0)), 0.5);
290      }
291      if (node.Symbol is Cube) {
292        return AutoDiff.TermBuilder.Power(
293          ConvertToAutoDiff(node.GetSubtree(0)), 3.0);
294      }
295      if (node.Symbol is CubeRoot) {
296        return AutoDiff.TermBuilder.Power(
297          ConvertToAutoDiff(node.GetSubtree(0)), 1.0 / 3.0);
298      }
299      if (node.Symbol is Sine) {
300        return sin(
301          ConvertToAutoDiff(node.GetSubtree(0)));
302      }
303      if (node.Symbol is Cosine) {
304        return cos(
305          ConvertToAutoDiff(node.GetSubtree(0)));
306      }
307      if (node.Symbol is Tangent) {
308        return tan(
309          ConvertToAutoDiff(node.GetSubtree(0)));
310      }
311      if (node.Symbol is Erf) {
312        return erf(
313          ConvertToAutoDiff(node.GetSubtree(0)));
314      }
315      if (node.Symbol is Norm) {
316        return norm(
317          ConvertToAutoDiff(node.GetSubtree(0)));
318      }
319      if (node.Symbol is StartSymbol) {
320        return ConvertToAutoDiff(node.GetSubtree(0));
321      }
322      throw new ConversionException();
323    }
324
325
326    // for each factor variable value we need a parameter which represents a binary indicator for that variable & value combination
327    // each binary indicator is only necessary once. So we only create a parameter if this combination is not yet available
328    private static Term FindOrCreateParameter(Dictionary<DataForVariable, AutoDiff.Variable> parameters,
329      string varName, string varValue = "", int lag = 0) {
330      var data = new DataForVariable(varName, varValue, lag);
331
332      AutoDiff.Variable par = null;
333      if (!parameters.TryGetValue(data, out par)) {
334        // not found -> create new parameter and entries in names and values lists
335        par = new AutoDiff.Variable();
336        parameters.Add(data, par);
337      }
338      return par;
339    }
340
341    public static bool IsCompatible(ISymbolicExpressionTree tree) {
342      var containsUnknownSymbol = (
343        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
344        where
345          !(n.Symbol is Variable) &&
346          !(n.Symbol is BinaryFactorVariable) &&
347          !(n.Symbol is FactorVariable) &&
348          !(n.Symbol is LaggedVariable) &&
349          !(n.Symbol is Constant) &&
350          !(n.Symbol is Addition) &&
351          !(n.Symbol is Subtraction) &&
352          !(n.Symbol is Multiplication) &&
353          !(n.Symbol is Division) &&
354          !(n.Symbol is Logarithm) &&
355          !(n.Symbol is Exponential) &&
356          !(n.Symbol is SquareRoot) &&
357          !(n.Symbol is Square) &&
358          !(n.Symbol is Sine) &&
359          !(n.Symbol is Cosine) &&
360          !(n.Symbol is Tangent) &&
361          !(n.Symbol is Erf) &&
362          !(n.Symbol is Norm) &&
363          !(n.Symbol is StartSymbol) &&
364          !(n.Symbol is Absolute) &&
365          !(n.Symbol is AnalyticQuotient) &&
366          !(n.Symbol is Cube) &&
367          !(n.Symbol is CubeRoot)
368        select n).Any();
369      return !containsUnknownSymbol;
370    }
371    #region exception class
372    [Serializable]
373    public class ConversionException : Exception {
374
375      public ConversionException() {
376      }
377
378      public ConversionException(string message) : base(message) {
379      }
380
381      public ConversionException(string message, Exception inner) : base(message, inner) {
382      }
383
384      protected ConversionException(
385        SerializationInfo info,
386        StreamingContext context) : base(info, context) {
387      }
388    }
389    #endregion
390  }
391}
Note: See TracBrowser for help on using the repository browser.